transforming math expression from text into calculated one

215
November 23, 2016, at 7:37 PM

inside certain calculation I'm generating an math expression in javascript like

var myExpression = '';
if (!isNaN(myVal) && myVal> 0) {
    myExpression += '(' + myVal+ ' * ' + someVal + ') +';                    
}

and based on certain user events I'm getting generated expression in console.log as you expect

(1 * 1) + (10 * 5) + ...

or

(10 * 5) + ...

How can I transform this math expression representation into real expression and to store it's result into variable?

Answer 1

You can use eval() on the string, which will run it as JavaScript. This will allow the math expression to be computed:

eval(myExpression);

Just note be wary of using eval(). See Why is using the JavaScript eval function a bad idea. Although that being said there are many things people can now do with the JavaScript built-in console, as users can execute any JavaScript they wish on any web page. See the third comment by of this answer byPrestaul on potential problems this can have. If you ensure that the variables cannot be directly manipulated by the user then your fine.

Answer 2

You can use math.js, which comes with it's own expression parser:

math.eval('(1 * 1) + (10 * 5)');  // 51

or provide variables in a scope and use them in the expression:

math.eval('(myVal * someVal)', {myVal: 2, someVal: 10});  // 20

you can also parse an expression into a tree and do operations on the tree, see docs:

http://mathjs.org/docs/expressions/parsing.html http://mathjs.org/docs/expressions/expression_trees.html

READ ALSO
jQuery Radio Button onChange Not Working

jQuery Radio Button onChange Not Working

I followed this example to capture an onChange() jQuery event for a radio button group:[nnn]JQuery $(#radioButton). change(.

939
jQuery Animate inline style issue

jQuery Animate inline style issue

[nnn]I cant fix one bug in my code. I create on click slide up/down div, but yet when i click it 4 times very fast my css top value is to height and function stop working.

326
jQuery draggable: append to same position

jQuery draggable: append to same position

I am creating dynamic tables that get added when a user clicks a button. .

353
Invoking method/scope issue in js class closure

Invoking method/scope issue in js class closure

I'm working on a jQuery plugin, and using the anonymous closure pattern to wrap the works. Internally I define an object prototype with several methods.

269