How to split a string by several possible characters?

Given the following string:

`cartwright.claude@yahoo.com\r
herminia.nolan@hotmail.com\n
xstokes@hotmail.com;
dameon85@jacobs.com;
camren86@gmail.com
preston13@jerde.org
kelley05@bosco.com,
vella46@gmail.com,
dhaag@hackett.com;
mreinger@gibson.com;`

I am trying to split the string by an array of characters [', ', '\r', '; ', '\n', ' ']. How can I achieve that?

1 answer

  • answered 2021-05-15 14:23 trincot

    You can use str.split(/[\s,;]+/). The downside is that it may leave an emtpy string at the end. To avoid that, you are probably better off with matching what you do want to get, i.e. using str.match:

    let str = `cartwright.claude@yahoo.com\r
    herminia.nolan@hotmail.com\n
    xstokes@hotmail.com;
    dameon85@jacobs.com;
    camren86@gmail.com
    preston13@jerde.org
    kelley05@bosco.com,
    vella46@gmail.com,
    dhaag@hackett.com;
    mreinger@gibson.com;`;
    
    let result = str.match(/[^\s,;]+/g);
    
    console.log(result);