How to split a string using multiple delimeters?

How to split a string using multiple delimeters?
Photo by Shaawn / Unsplash

You can split a string in JavaScript using multiple delimiters by providing a regular expression (regex) as the delimiter. The regex should include all the delimiters you want to split on.

const myString = "Hello, world; foo|bar";
const myArray = myString.split(/[ ,;|]+/);

console.log(myArray); // ["Hello", "world", "foo", "bar"]

In this example, the regular expression /[ ,;|]+/ matches one or more occurrences of a space, comma, semicolon, or pipe character. The split method then splits the string myString at each occurrence of one of these characters.

The resulting array myArray contains each word from the original string, with the delimiters removed.