简体   繁体   English

用运算符将​​数字分割成字符串

[英]split a string with numbers with operations

how can I split a string such as 我如何分割一个字符串,如

'11+4+3' into ['11', '+', '4', '+', '3'] ? '11+4+3'变成['11', '+', '4', '+', '3']吗?

or even turn array of 甚至将

[1, 1, '+', 4, '+', 3] into [11, '+', 4, '+', 3] ? [1, 1, '+', 4, '+', 3]变成[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() . 我也知道字符串的eval()会自动将字符串值添加到数字值中,但是我试图弄清楚如何在不使用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. 但是,它不会验证字符串是否具有所需的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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