0

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.

EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
Taieb
  • 920
  • 3
  • 16
  • 37

2 Answers2

2

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));
vibhor1997a
  • 2,336
  • 2
  • 17
  • 37
1

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());
}
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38