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
?
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().
Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With