I want to filter an array that only contains emails,
I did this
emails = emails.filter((x)=>(x !== (undefined || null || '')))
that delete the empty value, but can accept a value that is not an email.
I want to filter an array that only contains emails,
I did this
emails = emails.filter((x)=>(x !== (undefined || null || '')))
that delete the empty value, but can accept a value that is not an email.
You can use the regex from the accepted answer here
let 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,}))$/;
emails = emails.filter(e =>e && e.toLowerCase().match(re));
Using the regular expression found here you can complete your filter like so:
var emails = [];
emails = emails.filter(e => typeof e == "string" && validEmail(e));
console.log(emails);
function validEmail(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.toLowerCase());
}