Javascript Evaluating a string as a mathematical, Contains "()"

Viewed 74
var temp = '1000*(2-1)/2';

How do I parse and evaluate a mathematical expression in a string ('1000*(2-1)/2'). have "()". using javascript

1 Answers

You could use eval. Just be aware should then sanitize the string with a regex first to handle errors:

eval()

var temp = '1000*(2-1)/2';
// strip anything other than digits, (), -+/* and .
var str = temp.replace(/[^-()\d/*+.]/g, '');
console.log(eval(str));

Or you could use Function-constructor:

Function doc Mozilla developer

var temp = '1000*(2-1)/2';

function calc(value) {
  return new Function('return ' + value)();
}

console.log( calc(temp) );

Related