Last active
January 22, 2024 15:02
-
-
Save bboe/c9adabdc1368193879d0 to your computer and use it in GitHub Desktop.
Javascript email list parser with display name
This file contains hidden or 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 [email protected],, , [email protected] <[email protected]>,,, ",hello world, inc," <[email protected]> [email protected] '; | |
console.log(emails(test)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment