8

I have a string where I need to separate it by +-*/ and put it into array.

I've tried this code that I also found here, but it doesn't seem to be working. It gives me the error "Invalid regular expression: /+|-|*|//: Nothing to repeat."

var separators = ['+', '-', '*', '/'];
var numbers = x.split(new RegExp(separators.join('|'), ''));

Any advice on how should I do this?

AyakoS
  • 221
  • 2
  • 7
  • 18
  • Does the string contain special characters? – Harsha Sep 19 '17 at 06:55
  • the problem is that some of those characters have special meanings in a RegExp ... so you need to escape them with more \\ than you think – Jaromanda X Sep 19 '17 at 06:55
  • `+` and `*` have special significance in regex. Try `string.split(/[\+-\*\/]/g)` – Rajesh Sep 19 '17 at 06:55
  • @Harsha No. There's no special characters other than the four – AyakoS Sep 19 '17 at 06:59
  • 3
    Possible duplicate of [Split a string based on multiple delimiters](https://stackoverflow.com/questions/19313541/split-a-string-based-on-multiple-delimiters) – Durga Sep 19 '17 at 07:02

3 Answers3

14

Try this.

var str = "i-have_six*apples+doyou/know.doe";
console.log(str.split(/[.\*+-/_]/));
Durga
  • 15,263
  • 2
  • 28
  • 52
Harsha
  • 239
  • 1
  • 2
  • 10
5

Here is your answer,

x = "This+is*test/the*theunder-Yes";
var separators = ['\\\+', '-', '\\*', '/'];

var numbers = x.split(new RegExp(separators.join('|'),'g'));
console.log(numbers);

It is because, your +,* are regex related wild card characters. You can't use as is.

Rahul
  • 18,271
  • 7
  • 41
  • 60
2

use regex split

    var tempvar = (X).split(/[+-/*]+/);

This should return as array split. eg : X = 1+2-3/4

alert(x) would return as 

    1,2,3,4
Vipin Mohan
  • 1,631
  • 1
  • 12
  • 22