Javascript email list parser with display name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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