-1

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?

user1765862
  • 13,635
  • 28
  • 115
  • 220

2 Answers2

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.

Community
  • 1
  • 1
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
  • this is the bad solution. – The Reason Nov 03 '15 at 20:49
  • because i can pass some script into variables from the client side to execute it on a server. Also this is the bad habit to use _eval_ function – The Reason Nov 03 '15 at 20:51
  • 1
    @The The user can do that with or without `eval()`. Browsers have a JavaScript console built-in now a days, they can do that despite having `eval()` in the code. – Spencer Wieczorek Nov 03 '15 at 20:52
  • The _eval_ function open up your code for XSS attacks, this is not only my point. [link](https://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/) – The Reason Nov 03 '15 at 20:58
0

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

Jos de Jong
  • 6,602
  • 3
  • 38
  • 58