0

I need to split a string by multiple delimiters.

My string is var str = "2$4@3*5"

My array of delimiters (separators) is var del = ["$","@", "*"]

I'm using a regular expression but it is not working.

str.split(new RegExp(del.join('|'), 'gi'));

The results should be ["2","4","3","5"]

However I'm getting an error SyntaxError: Invalid regular expression: /*/: Nothing to repeat

When I remove the * the resulting array is ["2$3',"3", "5"]

How can I split with multiple delimiters from an array of delimiters?

and why does this not work with $ and *?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
xslibx
  • 4,249
  • 9
  • 35
  • 52

2 Answers2

1

You need to escape the special characters first - replace function from this answer:

var str = "2$4@3*5";    
var del = ["$", "@", "*"];    

const res = str.split(new RegExp(del.map(e => e.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|"), "gi"));
    
console.log(res);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Thank works great thank you! – xslibx Jul 05 '19 at 06:34
  • 1
    I would leave `RegExp.escape` separate, like in the [linked answer](https://stackoverflow.com/a/3561711/6231376), and map like `del.map(RegExp.escape)`. Much more readable. – TeWu Jul 05 '19 at 06:35
  • Yeah, but if you don't need to add it to the object, it's easier - plus you could just construct your own function @TeWu. – Jack Bashford Jul 05 '19 at 06:36
0

Try like this.

I passed in the Regex expression in split.

var str = "2$4@3*5"

var res=  str.split(/[$,@,*]+/)

console.log(res)
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
  • The array of delimiters needs to be dynamic which is why I prefer Jack's answer in this case. – xslibx Jul 05 '19 at 06:42