Friday 14 June 2019

javascript - How to split emails by no space , comma , semi-colon, and space using Regex?



I'm trying to split emails by no space, comma, semi-colon, and space using Regex. I have this string:



var emails = "user1@email.comuser2gmail.com user3@email.com;user4@gmail.com, user5@email.com"


and I'm trying to get all emails in putll them in an array using this Regex:




function extractEmails() {
return emails.match(/\w+@\w+.com/);
}


but it doesn't seem to be working. Any ideas on how get all emails using Regex? Thank you in advance!


Answer



All you need to do is add the g modifier, to get all matches:






var emails = "user1@email.comuser2gmail.com\nuser3@email.com;user4@gmail.com, user5@email.com";

function extractEmails() {
return emails.match(/\w+@\w+.com/g);
}

console.log(
extractEmails(emails)

);





(This will only work as long as none of the part before the @ contains .com, of course, and should there be a barcom.com domain it would fail as well ...)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...