Split a string based on multiple delimiters
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);
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
)
Solution 4
I think you would need to escape the +, * and ?, since they've got special meaning in most regex languages
Solution 5
This is because characters like +
and *
have special meaning in Regex.
Change your join from |
to |\
and you should be fine, escaping the literals.
Comments
-
Okky almost 2 years
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?
-
Okky over 10 yearsI'm getting error when I changed it to |\ 'Uncaught SyntaxError: Unexpected token ;' I think it is because when |\ is entered inside quote the quote is getting escaped. How to avoid that?
-
anubhava over 10 yearsCan you provide an example of var x?
-
nim over 9 yearsvar arr = str.split(new RegExp('[|!=&+- ]', 'g'));- error
-
HussienK about 8 yearsThis works great! what exactly is
new RegExp(separators.join('|'), 'g')
doing here though? -
melc about 8 years@HussienK enables alternation in the expression, look here regular-expressions.info/alternation.html
-
Luddens Desir about 5 yearsMan. The RegEx. This is why I've taken so long to actually learn them. Why the heck does the + have three slashes in front, but the * have 2 slashes, and the :, / and space have none?