Split a string based on multiple delimiters

I was trying to split a string based on multiple delimiters by referring How split a string in jquery with multiple strings as separator

Since multiple delimiters I decided to follow

var separators = [' ', '+', '-', '(', ')', '*', '/', ':', '?'];
var tokens = x.split(new RegExp(separators.join('|'), 'g'));​​​​​​​​​​​​​​​​​

But I'm getting error

Uncaught SyntaxError: Invalid regular expression: / |+|-|(|)|*|/|:|?/: Nothing to repeat 

How to solve it?


Solution 1:

escape needed for regex related characters +,-,(,),*,?

var x = "adfds+fsdf-sdf";

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

http://jsfiddle.net/cpdjZ/

Solution 2:

This should work:

var separators = [' ', '+', '(', ')', '*', '\\/', ':', '?', '-'];
var tokens = x.split(new RegExp('[' + separators.join('') + ']', 'g'));​​​​​​​​​​​​​​​​​

Generated regex will be using regex character class: /[ +()*\/:?-]/g

This way you don't need to escape anything.

Solution 3:

The following would be an easier way of accomplishing the same thing.

var tokens = x.split(new RegExp('[-+()*/:? ]', 'g'));​​​​​​​​​​​​​​​​​

Note that - must come first (or be escaped), otherwise it will think it is the range operator (e.g. a-z)