I've been trying to split a string by numbers. Basically I have a string such as:
"10x + 10"
JS splits it and gets:
["+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:
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 .
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.