1

I'm designing a simple calculator with HTML & JavaScript. Essentially, when the "equals" button is clicked, the expression the user entered with the calculator buttons is stored in a string variable, userInput, and eval(userInput) gets the answer. Is there an alternative way to calculate the result without using eval()?

Update:

Thanks for the comments,

function calculateStr(userInput) {
    return new Function('return ' + equation)();
}

calculateStr(userInput)

works well.

ScopeY
  • 39
  • 2
  • 11
  • 1
    Sure just parse the expression and calculate the result. – kemiller2002 Feb 23 '17 at 15:56
  • 1
    This is bordering on too broad for an answer but in general yes of course there is otherwise computer programming languages wouldnt be a thing. It involves parsing your equation and executing the result. Or just use mathjs: http://mathjs.org/docs/expressions/parsing.html – Jamiec Feb 23 '17 at 15:57
  • 2
    There are many questions matching the search ["\[js\] evaluate expression without eval"](/search?q=%5Bjs%5D+evaluate+expression+without+eval), surely one or more answer this. – T.J. Crowder Feb 23 '17 at 15:57
  • @T.J.Crowder, cool, a search page as dupe target :) – Nina Scholz Feb 23 '17 at 16:05

0 Answers0