Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"; alert(eval(apa)); 

So, does anyone know about alternatives to eval?

like image 727
Eric Herlitz Avatar asked Jun 25 '11 17:06

Eric Herlitz


People also ask

What can I use instead of eval in JavaScript?

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().

Why we should not use eval in JavaScript?

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!


1 Answers

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 
like image 127
yckart Avatar answered Oct 10 '22 04:10

yckart