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?

5
  • Does the string contain special characters? Commented Sep 19, 2017 at 6: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 Commented Sep 19, 2017 at 6:55
  • + and * have special significance in regex. Try string.split(/[\+-\*\/]/g) Commented Sep 19, 2017 at 6:55
  • @Harsha No. There's no special characters other than the four Commented Sep 19, 2017 at 6:59
  • 3
    Possible duplicate of Split a string based on multiple delimiters Commented Sep 19, 2017 at 7:02

3 Answers 3

14

Try this.

var str = "i-have_six*apples+doyou/know.doe";
console.log(str.split(/[.\*+-/_]/));

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Where is the related question?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.