Skip to content

Instantly share code, notes, and snippets.

@bboe
Last active January 22, 2024 15:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bboe/c9adabdc1368193879d0 to your computer and use it in GitHub Desktop.
Save bboe/c9adabdc1368193879d0 to your computer and use it in GitHub Desktop.
Javascript email list parser with display name
function display_name(text) {
/* Remove all quotes
Remove whitespace, brackets, and commas from the ends. */
return text.replace(/(^[\s,>]+)|"|([\s,<]+$)/g, '');
}
function emails(addr_list) {
/* Regex source:
https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
*/
var email_re = /[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/g;
var emails = [], match, idx = 0;
while (match = email_re.exec(addr_list)) {
var display;
if (display = display_name(addr_list.substring(idx, match['index']))) {
emails.push('"' + display + '" ' + '<' + match[0] + '>');
}
else {
emails.push(match[0]);
}
idx = match['index'] + match[0].length;
}
return emails;
}
var test = 'a b c a@a.com,, , b@b.com <c@c.com>,,, ",hello world, inc," <a@a.com> slkjdsf.slkj+foo@gmail.com ';
console.log(emails(test));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment