简体   繁体   中英

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() .

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

Output :

["11", "+", "3", "+", "4"]
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM