[英]Split string with numbers
I've been trying to split a string by numbers. 我一直在尝试用数字分割字符串。 Basically I have a string such as:
基本上我有一个字符串,例如:
"10x + 10"
JS splits it and gets: JS将其拆分并得到:
["+10x", "+10"]
I've tried doing this a few times but haven't hit success. 我已经尝试过几次,但是都没有成功。 If I understand it right I just need to split it by
+ - / *
. 如果我理解正确,我只需要用
+ - / *
将其分开。 My best attempt was this: 我最大的尝试是:
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);
}
}
But it doesn't work. 但这是行不通的。 Also I only want
+
and -
to be in front on the array elements and not *
and /
. 我也只希望
+
和-
在数组元素的前面,而不是*
和/
。 If anyone could help me with this is would be much appreciated. 如果有人可以帮助我,将不胜感激。
Keep in mind that Array.prototype.split()
can take a regular expressions: 请记住,
Array.prototype.split()
可以使用正则表达式:
let str = "10x + 10";
let arr = str.split(/[+|-|\*|/]/);
console.log(arr); // output: ["10x ", " 10"];
This is not a good way to parse arithmetical expressions, though. 但是,这不是解析算术表达式的好方法。 To do that, I recommend the Shunting-yard algorithm .
为此,我建议使用Shunting-yard算法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.