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";
alert(eval(apa));
So, does anyone know about alternatives to eval
?
Mhh, you could use the Function
-constructor:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
function evil(fn) {
return new Function('return ' + fn)();
}
console.log( evil('12/5*9+9.4*2') ); // => 40.4