Thursday 17 March 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...