javascripteval

Calculate string value in javascript, not using eval


Is there a way to calculate a formula stored in a string in JavaScript without using eval()?

Normally I would do something like

var apa = "12/5*9+9.4*2";
console.log(eval(apa));

So, does anyone know about alternatives to eval()?


Solution

  • This is exactly the place where you should be using eval(), or you will have to loop through the string and generate the numbers. You will have to use the Number.isNaN() method to do it.