I have this little example:
var myoperation = "2+2";
var myoperation2="2*5/3";
var myoperation3="3+(4/2)"
is there anyway to execute this and get a result?
Thanks a lot in advance!
I have this little example:
var myoperation = "2+2";
var myoperation2="2*5/3";
var myoperation3="3+(4/2)"
is there anyway to execute this and get a result?
Thanks a lot in advance!
Use eval
MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval
Some people say it is evil, but it was designed for this exact purpose;
console.log(eval(myoperation)); // 4
console.log(eval(myoperation2)); // 3.33
console.log(eval(myoperation3)); // 5
You can use eval
for this.
Don't pass any data from a remote server to eval
before validating it. Damage can be done with eval
.
You could do this besides eval
:
function run(myoperation) {
return new Function('return ' + myoperation + ';').call();
}
run('2+2'); // return 4