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
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
You could use eval. Just be aware should then sanitize the string with a regex first to handle errors:
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) );