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.