Metallica Metallica - 1 month ago 5
Javascript Question

breaking apart a math expression in javascript

I have a text-box in which the input is a simple math expression like

2+323*4.5/5
or
2 + 323*4.5 /5
(I mean the white spaces should be ignored). Both integers and floats are possible and acceptable as input. I want to break apart every element of this expression (both operands and operators) and save them into an array, so that I can send the first operand, the first operator, and the second operand (as parameters of an atomic calculation) to a PHP page (server) and then after getting the server's response, send the second operator and the third operand together with the server's previous response in order to perform another atomic operation and so on.

For example, if the initial string is
2 + 323*4.5 /5
, my array (the result) should look like this:

[2, +, 323, *, 4.5, /, 5].

I used the match method as follows:

var expr = document.getElementById("txtExpr").value;
var tokens = expr.match(/-*\/?[0-9]/g);


But I can't use "+" sign and the result array is not what I'm looking for. It concatenates the operator to the next operand.

PS: I NEED TO ACCEPT/GET NEGATIVE NUMERS AS WELL.

Answer Source
"2 + 323*4.5 / 5".match(/\d*\.\d+|\d+|[/*+-]/g);
// >> ["2", "+", "323", "*", "4.5", "/", "5"]