Skip to content Skip to sidebar Skip to footer

Extract Name And Email From String In Js

How can I extract the name and email from a string, where emails are separated by commas. The regex below works great for individual emails, but not for emails within a string. (?

Solution 1:

It's hard to tell if the data will change or remain the same, but here's my attempt:

var re  = /(?:"?([A-Z][^<"]+)"?\s*)?<?([^>\s,]+)/g;

while (m = re.exec(str)) {
  if(m[1]) { m[1] = m[1].trim() }
  console.log("Name: "  + m[1]);
  console.log("Email: " + m[2]);
}

Working Demo

Solution 2:

Here is one possible answer:

(?:^|, *)(?![^",]+")(?:((?=[^"<]+@)|(?![^"<]+@)"?(?<name>[^"<]*)"? *))<?(?<email>[^,>]*)>?

This is using ruby regexes, and uses forward matches to determine if an entry has a name.

  1. (?:^|, *): start at the front of the string, or after a , and a number of spaces
  2. (?![^",]+"): negative lookahead, abort match if there are some characters and then a ". This stops commas from starting matches inside strings.
  3. (?:((?=[^"<]+@)|(?![^"<]+@)"?(?<name>[^"<]*)"? *)): matching the name:

    1. (?=[^"<]+@) if a @ occurs before a quote or open brace, it is just a email address without name, so do no match
    2. (?![^"<]+@)"?(?<name>[^"<]*)"? *): otherwise, match the name (skipping the open and close quote if they are present
  4. <?(?<email>[^,>]*)>?: match the email.

On rubular

Note that for a real job, this would be a terrible approach. The regex is near incomprehensible, not to mention fragile. It also isn't complete, eg what happens if you can escape quotes inside the name?

I would write a dedicated parser for this if you really need it. If you are just trying to extract some data though, the regex may be good enough.

Post a Comment for "Extract Name And Email From String In Js"