Categories
JavaScript Answers

How to Split a string based on multiple delimiters with JavaScript?

Spread the love

To split a string based on multiple delimiters with JavaScript, we can create a regex that matches all the delimiters and use that with the JavaScript string’s split method.

For instance, we can write:

const x = "adfds+fsdf-sdf";
const separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
const tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);

We have the x string we want to split into a string array by the + and – signs.

Then we define the separators array with the delimiters we want to split the string by.

Next, we have new RegExp(separators.join('|'), 'g') to create the regex that matches all the delimiters listed in separators.

The | symbol lets us match any of the delimuters above.

The 'g' flag searches for all matches of the pattern in the string.

Finally, we call split with the regex to split the string.

Therefore, we get ["adfds","fsdf","sdf"] as a result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *