Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
Okky Avatar asked Oct 11 '13 08:10

Okky


People also ask

How do you split a string with multiple separators?

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.

Can I split a string by two delimiters Python?

Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.


2 Answers

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/

like image 71
melc Avatar answered Sep 24 '22 07:09

melc


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.

like image 39
anubhava Avatar answered Sep 25 '22 07:09

anubhava