[英]Split string with numbers
我一直在嘗試用數字分割字符串。 基本上我有一個字符串,例如:
"10x + 10"
JS將其拆分並得到:
["+10x", "+10"]
我已經嘗試過幾次,但是都沒有成功。 如果我理解正確,我只需要用+ - / *
將其分開。 我最大的嘗試是:
var statement = ["10x + 10"]
var spliters = ['+', '-', '*', '/'];
for (i = 0; i < spliters.length; i++) {
for (o = 0; o < statement.length; o++) {
statement[o] = statment[o].split(spliters[i]);
for (p = 0; p < statment[o].length - 1; p++) {
statement[o][p] = spliters[i] + statement[o][p];
}
statement = flatten(statement);
}
}
但這是行不通的。 我也只希望+
和-
在數組元素的前面,而不是*
和/
。 如果有人可以幫助我,將不勝感激。
請記住, Array.prototype.split()
可以使用正則表達式:
let str = "10x + 10";
let arr = str.split(/[+|-|\*|/]/);
console.log(arr); // output: ["10x ", " 10"];
但是,這不是解析算術表達式的好方法。 為此,我建議使用Shunting-yard算法 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.