使用RegEx过滤对象数组?在角度5-9

如何使用RegExp过滤对象(包括标题,电子邮件和名称)

标题和名称只能使用字母。 电子邮件应该有效

RegExp模式:

电子邮件= /[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}/

标题和名称= / ^ [A-Za-z] + $ /

如果任何一封电子邮件无效,则该无效电子邮件应存储在不同的变量中,而其他对象应存储在不同的变量中。

在JSON中,第一个对象电子邮件无效,因此我想将此对象存储在其他变量中

items = [
{
    title: "This is title", 
    email: "testtest.com",
    status: "confirmed"
},
{
    title: "This another one", 
    email: "someone@something.com",
    status: "pending"
{    
    title: "Just a random string", 
    email: "me@you.co.uk",
    status: "pending"
{    
]
评论
菊花开
菊花开

If you only want to filter out to filter out emails that are invalid based on the regex rule, you can use Array.filter() on the items array, and filter out any objects whose email does not match the regex. You can use text or match for your regex matching.

这是您可以执行的操作:

const items = [{
    title: "This is title",
    email: "testtest.com",
    status: "confirmed"
  },
  {
    title: "This another one",
    email: "someone@something.com",
    status: "pending"
  },
  {
    title: "Just a random string",
    email: "me@you.co.uk",
    status: "pending"
  }
];

const emailRegex = new RegExp(/[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}/)
const titleRegex = new RegExp('/^[A-Za-z]+$/');

const res = items.filter(({
  title,
  email
}) => !email.match(emailRegex));
console.log(res)

const res2 = items.filter(({
  title,
  email
}) => !emailRegex.test(email));
console.log(res2)
点赞
评论
xnobis
xnobis

请测试这种方法

var items = [
{
    title: "This is title", 
    email: "testtest.com",
    status: "confirmed"
},
{
    title: "This another one", 
    email: "someone@something.com",
    status: "pending"
},
{    
    title: "Just a random string", 
    email: "me@you.co.uk",
    status: "pending"
}    
]

var filtered_not_matching = items.filter(s => !/[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}/.test(s.email))

console.log(filtered_not_matching)

The .test() API runs a search for a match between a RegExp and a String.

请在javascript中找到以下有关正则表达式匹配的文章,您可以找到一些与正则表达式匹配的API

https://ultimatecourses.com/blog/understanding-regular-expression-matching-with-test-match-exec-search-and-split

点赞
评论