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?
Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.
Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With