-1

Hi there I am searching for regex to split emails, but no success so far. What is the point I want to make possible to separate this:

o@gmail.com b@gmail.com c@gmail.om

or

o@gmail.com, b@gmail.com,c@gmail.com

or

o@gmail.com,
 b@gmail.com, c@gmail.com
O.Kotsik
  • 21
  • 5
  • Does this answer your question? [How to validate an email address in JavaScript](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript) – Celsiuss Dec 23 '19 at 00:46
  • when you do the string .split, use this regex: /\s+|,/g (it will search for spaces, or comma, or tabs, or new lines, or returns). ex: console.log(s.split(/\s+|,/g)) – wakakak Dec 23 '19 at 00:50
  • @Celsiuss, no, I am searching more on how to separate lines here, because of dealing with multiple emails – O.Kotsik Dec 23 '19 at 00:51
  • How does that not answer it? Use regex, execute it on your string, iterate over the matches and you got your emails. – Celsiuss Dec 23 '19 at 00:57

2 Answers2

1

You need to split on either a comma surrounded by some number of white-space characters, or just one or more white-space characters:

let strs = ['o@gmail.com b@gmail.com c@gmail.om',
'o@gmail.com, b@gmail.com,c@gmail.com',
'o@gmail.com,\n\
 b@gmail.com, c@gmail.com'];

console.log(strs.map(s => s.split(/\s*,\s*|\s+/)))
Nick
  • 138,499
  • 22
  • 57
  • 95
1

You regex should be ,\s*|\s+:

  • first part ,\s* takes anything with comma followed by 0 or more whitespaces (whitespace is defined as \n, \r, \t, \f, or " "), so e.g. space + new line + space
  • second part \s+ takes one or more whitespaces (without coma).

Example:

var emails = `o@gmail.com b@gmail.com,o@gmail.com,
 b@gmail.com, c@gmail.com
o@gmail.com b@gmail.com`

test.split(/,\s*|\s+/); // <- splits to 7 emails
Tomas
  • 1,849
  • 1
  • 13
  • 13