Calculate string value in javascript, not using eval

Eric Herlitz picture Eric Herlitz · Jun 25, 2011 · Viewed 63.8k times · Source

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?

Answer

yckart picture yckart · Aug 6, 2013

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