I'm trying to split the mathematical strings on maths operators. for example
expression = "7*6+3/2-5*6+(7-2)*5"
I need to tokenize it to produce:
expressionArray = ["7","*","6","+","3","/","2","-","5","*","6"]
I tried finding the solution here and this is what i get
expressoinArray=expression.split("(?<=[-+*/])|(?=[-+*/]")
but looks like this is not fetching the desired result for expression
.
jsfiddle
var expression = "7.2*6+3/2-5*6+(7-2)*5";
var copy = expression;
expression = expression.replace(/[0-9]+/g, "#").replace(/[\(|\|\.)]/g, "");
var numbers = copy.split(/[^0-9\.]+/);
var operators = expression.split("#").filter(function(n){return n});
var result = [];
for(i = 0; i < numbers.length; i++){
result.push(numbers[i]);
if (i < operators.length) result.push(operators[i]);
}
console.log(result);
EDIT:
This works like the accepted answer and as a bonus won't fail due to filter()
in IE8 and below:
var expression = "7.2*6+3/2-5*6+(7-2)*5";
var splitUp = expression.match(/[^\d()]+|[\d.]+/g);
document.body.innerHTML = splitUp;
http://jsfiddle.net/smAPk/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With