Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Last active September 27, 2017 04:29
Show Gist options
  • Select an option

  • Save sandcastle/4b757c545836e7387625291d21f9e33c to your computer and use it in GitHub Desktop.

Select an option

Save sandcastle/4b757c545836e7387625291d21f9e33c to your computer and use it in GitHub Desktop.
Parse a list of emails separated by comma (,) or semicolon (;)
/**
* 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, '');
}
}
@sandcastle

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment