Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a mathematical expression on operators and include the operators in the output array

Tags:

javascript

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.

like image 312
min2bro Avatar asked Dec 05 '22 10:12

min2bro


2 Answers

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);
like image 66
Gabe Avatar answered Feb 13 '23 03:02

Gabe


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/

like image 43
Alex W Avatar answered Feb 13 '23 03:02

Alex W