Split a string based on multiple delimiters

75,082

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)

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.

Share:
75,082
Okky
Author by

Okky

Learn more, eat more, travel more

Updated on July 09, 2022

Comments

  • Okky
    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
    Okky over 10 years
    I'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
    anubhava over 10 years
    Can you provide an example of var x?
  • nim
    nim over 9 years
    var arr = str.split(new RegExp('[|!=&+- ]', 'g'));- error
  • HussienK
    HussienK about 8 years
    This works great! what exactly is new RegExp(separators.join('|'), 'g') doing here though?
  • melc
    melc about 8 years
    @HussienK enables alternation in the expression, look here regular-expressions.info/alternation.html
  • Luddens Desir
    Luddens Desir about 5 years
    Man. 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?