0

I have the following string

str = "11122+3434"

I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *

I have tried the following

strArr = str.split(/[+,-,*,/]/g)

But I get

strArr = [11122, 3434]
4
  • there can be different delimiters or there can be one at a time Commented Sep 28, 2016 at 4:54
  • you want to split only mathematical expressions or anything else? Commented Sep 28, 2016 at 4:55
  • only one delimiter at a time. I want to split only mathematical expressions Commented Sep 28, 2016 at 4:55
  • keep it simple, str.split(/([-+*/])/) Commented Sep 28, 2016 at 5:26

5 Answers 5

4

Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.

In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).

For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:

var result = str.match(/(\d+)([+,-,*,/])(\d+)/);

returns an array:

["11122+3434", "11122", "+", "3434"]

So your values would be result[1], result[2] and result[3].

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

Comments

2

This should help...

str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)

Comments

1

Hmm, one way is to add a space as delimiter first.

// yes,it will be better to use regex for this too
str = str.replace("+", " + ");

Then split em

strArr = str.split(" ");

and it will return your array

["11122", "+", "3434"]

Comments

1

in bracket +-* need escape, so

strArr = str.split(/[\+\-\*/]/g)

1 Comment

this won't give you the symbols.
0

var str = "11122+77-3434";

function getExpression(str) {
  var temp = str.split('');
  var part = '';
  var result = []
  for (var i = 0; i < temp.length; i++) {
    if (temp[i].match(/\d/) && part.match(/\d/g)) {
      part += temp[i];
    } else {
      result.push(part);
      part = temp[i]
    }
    if (i === temp.length - 1) { //last item
      result.push(part);
      part = '';
    }
  }
  return result;
}
console.log(getExpression(str))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.