jyoon006
jyoon006

Reputation: 809

split a string with numbers with operations

how can I split a string such as

'11+4+3' into ['11', '+', '4', '+', '3']?

or even turn array of

[1, 1, '+', 4, '+', 3] into [11, '+', 4, '+', 3]?

splitting the string with regexp of

/[^0-9]/g 

will split into numbers I want but will remove the operation values. I need a way so that I can keep the operation values as well. I also know that eval() of the string will automatically add the string values into number values but I'm trying to figure out how to add the string of numbers and operations without using eval().

Upvotes: 2

Views: 436

Answers (2)

alifirat
alifirat

Reputation: 2927

var str = "11+3+4";    
console.log(str.split(/(\+)/));

Output :

["11", "+", "3", "+", "4"]

Upvotes: 5

Katana314
Katana314

Reputation: 8610

function parseAsParts(input) {

  if (input instanceof Array) {
    input = input.join('');
  }
  var retVal = [];
  var thisMatch = null;
  var partSearch = /(\d+|[+-=])/g;
  while (thisMatch = partSearch.exec(input)) {
    retVal.push(thisMatch[0]);
  }
  return retVal;
}

That seems to get what you wanted. You can add more characters to look for inside of the regexp where it has "+-=". It won't verify that the string has the format you want though.

Upvotes: 0

Related Questions