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

Time:10-18

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

  1. with name name <[email protected]>
  2. without name [email protected]

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

List of examples :
[email protected],name1 <[email protected]>,[email protected]
or
[email protected],[email protected],[email protected]
or
[email protected] [email protected] name2 <[email protected]>
or
[email protected] [email protected] [email protected]
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 protected] and I still confused with how to do it including the name format name <[email protected]>?

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 protected] name <[email protected]>
==> ["[email protected]","name <[email protected]>"]

CodePudding user response:

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 = `
[email protected],name2 <[email protected]>,[email protected]
[email protected],[email protected],[email protected]
[email protected] [email protected] name9 <[email protected]>
[email protected] [email protected] [email protected]
name13 <[email protected]>
[email protected]
[email protected]
[email protected]
`;

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

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related