如何使用RegExp过滤对象(包括标题、电子邮件和名称)
title & name只应以字母形式显示。电子邮件应有效
RegExp模式:
电子邮件= /a-zA-Z0-9.-{1,}@a.-{2,}.{1}a-Za-Z2,}/
标题和名称= /^A+$/
如果任何一封电子邮件无效,则该无效电子邮件应存储在不同的变量中&其他对象应存储在不同的变量中。
在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"
{
]
发布于 2020-05-09 13:13:45
请测试这种方法
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)
.test()
API运行搜索RegExp和字符串之间的匹配。
请在javascript中找到下面关于regex匹配的文章,您可以找到一些关于regex匹配的API。
发布于 2020-05-09 13:09:08
如果只希望筛选出基于regex规则无效的电子邮件,则可以在items
数组上使用items
,并筛选出email
与正则表达式不匹配的任何对象。您可以使用文本或匹配进行正则表达式匹配。
你可以这样做:
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)
https://stackoverflow.com/questions/61697085
复制相似问题