在每次出现算术运算符时拆分一个字符串

时间:2016-11-08 20:15:14

标签: javascript string split

我有以下变量

var arithmetic = "96-66.33+99.3/22*58.2";
var arr;
var operator = "/*+-^";

我希望分割 arithmetic每{strong>一次或index operator变量。

最终结果将是["96", "-66.33", "+99.3", "/22", "*58.2"];

V.Roudge提供的最终解决方案



var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/(?=[-+*\/])/);
console.log(arithmetic);




4 个答案:

答案 0 :(得分:2)

最近,我可以通过正则表达式。非常接近,但现在还不是。

var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/([-+*\/])/g);
console.log(arithmetic);
编辑:知道了。

var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/(?=[-+*\/])/);
console.log(arithmetic);



var arithmetic = "96-66.33+99.3/22*58.2";
arithmetic = arithmetic.split(/(?=[-+*\/])/);
console.log(arithmetic);




答案 1 :(得分:1)

为它写了一个简单的解析器..但我认为正则表达式更好。



var arithmetic = "96-66.33+99.3/22*58.2";
var operator = {
    "+": true,
    "-": true, 
    "*": true, 
    "/": true 
};
var tokenList = [];
var token = "";
var op = "";
for (var i = 0; i < arithmetic.length; ++i) {
    if (operator[arithmetic[i]]) {
        tokenList.push(op + token);
        token = "";
        op = arithmetic[i];
    } else {
        token += arithmetic[i];
    }
}
tokenList.push(op + token);
console.log(tokenList);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
var arithmetic = "96-66.33+99.3/22*58.2";
var arr;
var operator = "/*+-^";

for(var i = 0; i < operator.length; i++){
  if(i==0)
    {
  arr = arithmetic.split(operator[i]);
      }
  else 
    {
     arr = arr.toString().split(operator[i]);
    }
  
  
}
console.log(arr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
var arithmetic = "96-66.33+99.3/22*58.2";
var arr=[];
var operator = "/*+-^";

var re = /[+-\/\*]/;
   
  arr = arithmetic.split(re);
  

console.log(arr);
&#13;
&#13;
&#13;