How do I split a list of emails with multiple formats in JavaScript?

0

Issue

I have a list of emails and the email have two formats:

  1. with name name <email@address.com>
  2. without name email@address.com

I am wondering if there is a way to split this list with different separators in Javascript.

List of examples :
email@address.com,name1 <email1@address.com>,email2@address.com
or
email@address.com,email1@address.com,email2@address.com
or
email@address.com email1@address.com name2 <email2@address.com>
or
email@address.com email1@address.com email2@address.com
or

email@address.com
name1 <email1@address.com>
email2@address.com

or

email@address.com
email1@address.com
email2@address.com

For the moment I split the list with the three separators for the simple email format email@address.com and I still confused with how to do it including the name format name <email@address.com>?

Here is the code I used for that:

    var emailInput = $(this);
    var clipboardData = e.originalEvent.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData('Text');
    var emails = pastedData.split(/[\r,\s]+/);

What I need to extract for example
email@adress.com name <email@address.com>
==> ["email@address.com","name <email@address.com>"]

Solution

Assuming you are not looking for an email address validator, and already know that your list has email addresses, then you can do:

let data = `
email1@address.com,name2 <email2@address.com>,email3@address.com
email4@address.com,email5@address.com,email6@address.com
email7@address.com email8@address.com name9 <email9@address.com>
email10@address.com email11@address.com email12@address.com
name13 <email13@address.com>
email14@address.com
email15@address.com
email16@address.com
`;

let result = data.match(/[^,;<>\s]+@[^,;<>\s]+|[^,;<>\s]+\s+<[^,;<>\s]+@[^,;<>\s]+>/g);

console.log(result);

Answered By – trincot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More