Last active
September 27, 2017 04:29
-
-
Save sandcastle/4b757c545836e7387625291d21f9e33c to your computer and use it in GitHub Desktop.
Parse a list of emails separated by comma (,) or semicolon (;)
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
| /** | |
| * Regex source: https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address | |
| */ | |
| const EMAIL_REGEX = /[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; | |
| /** | |
| * Parse a list of valid emails from the specified text. | |
| * | |
| * @param {String} text The string of email addresses to parse. | |
| * @returns {[{email: String, name: String}]} | |
| */ | |
| function parseEmailList(text) { | |
| let emails = [], | |
| match, idx = 0; | |
| while (match = EMAIL_REGEX.exec(text)) { | |
| const value = extractEmail(idx, match); | |
| if (value.isValid) { | |
| emails.push(value); | |
| } | |
| idx = match['index'] + match[0].length; | |
| } | |
| return emails; | |
| function extractEmail(idx, match) { | |
| var display; | |
| if (display = displayName(text.substring(idx, match['index']))) { | |
| return createEmail(match[0], display); | |
| } else { | |
| return createEmail(match[0]); | |
| } | |
| } | |
| function createEmail(email, name) { | |
| return { | |
| email: email || '', | |
| name: name || '', | |
| isValid: !!(email || '').length, | |
| }; | |
| } | |
| function displayName(text) { | |
| /* Remove all quotes, whitespace, brackets, and commas from the ends. */ | |
| return text.replace(/(^[\s,;>]+)|"|([\s,;<]+$)/g, ''); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspiration: https://gist.github.com/bboe/c9adabdc1368193879d0