How to split a string by several possible characters?

Given the following string:


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 = `\r\n;;,,;;`;
    let result = str.match(/[^\s,;]+/g);