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]
Neeraj
  • 58
  • 1
  • 3
  • 9

5 Answers5

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].

slebetman
  • 109,858
  • 19
  • 140
  • 171
2

This should help...

str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)
Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
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"]
deviantxdes
  • 469
  • 5
  • 17
1

in bracket +-* need escape, so

strArr = str.split(/[\+\-\*/]/g)
velen
  • 164
  • 1
  • 4
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))
Pankaj
  • 954
  • 8
  • 15