Skip to content

Instantly share code, notes, and snippets.

@bboe
Last active Aug 12, 2021
Embed
What would you like to do?
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