我有一个逗号分隔的字符串值,我试图将其拆分和清除以获取有效的电子邮件。虽然我已经能够将字符串拆分成一个数组,并且具有验证电子邮件地址的数组项的功能,但它似乎并没有遍历每一项并将有效的项推送到新数组中。目前,我只推送了一个值。
提供的字符串:
'test@gmail.com, email, nice@test.com'
以下是功能:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function emailParser(emailString){
var preFilterEmails = emailString.split(",");
var postFilterEmails = [];
for(i = 0; i < preFilterEmails.length; i++){
console.log(preFilterEmails);
if(validateEmail(preFilterEmails[i])){
console.log("Filtered");
console.log(preFilterEmails[i]);
postFilterEmails.push(preFilterEmails[i])
}
}
return postFilterEmails;
}
当前输出:
[ 'test@gmail.com', ' email', ' nice@test.com' ]
Filtered
test@gmail.com
[ 'test@gmail.com', ' email', ' nice@test.com' ]
[ 'test@gmail.com', ' email', ' nice@test.com' ]
[ 'test@gmail.com' ]
答案 0 :(得分:1)
这是因为逗号后出现空格。您可以在trim()
之后的split()
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function emailParser(emailString){
var preFilterEmails = emailString.split(",").map(x=>x.trim());
var postFilterEmails = [];
for(i = 0; i < preFilterEmails.length; i++){
console.log(preFilterEmails);
if(validateEmail(preFilterEmails[i])){
console.log("Filtered");
console.log(preFilterEmails[i]);
postFilterEmails.push(preFilterEmails[i])
}
}
return postFilterEmails;
}
console.log(emailParser('test@gmail.com, email, nice@test.com'));
答案 1 :(得分:0)
尝试使用内置的Array.filter()
(以及Array.map()
和String.trim()
来删除多余的空格):
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const emailString = 'test@gmail.com, email, nice@test.com';
let emails = emailString.split(',')
.map(s => s.trim())
.filter(s => re.test(s));
console.log(emails);