0

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!

Gabriel R.
  • 41
  • 2
  • 7
  • 1
    What all operations can the string have? – Dogbert May 19 '13 at 13:22
  • 1
    `eval`, which is also evil. – Antony May 19 '13 at 13:24
  • 1
    There's eval, or there's creating a script to parse the file manually. Which you use depends on how much effort you're willing to spend, and whether this is user input or not. – Qantas 94 Heavy May 19 '13 at 13:25
  • 1
    `eval()` seems to work just fine. However, unless it is used very judiciously and cautiously, it would really break your code. – Achrome May 19 '13 at 13:26
  • eval will parse and execute whatever is in the string, but it's slow and can be dangerous. The only other option would be to parse the string and do the calculations yourself. – adeneo May 19 '13 at 13:26

6 Answers6

3

You can use the eval() function. For eg: eval("2+2")

draxxxeus
  • 1,503
  • 1
  • 11
  • 14
2

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
GriffLab
  • 2,076
  • 3
  • 20
  • 21
  • It can run any JavaScript code inputted. I'd say PHP's `eval()` is dangerous, but in JavaScript... whats the worst that could happen? – Havenard May 19 '13 at 13:27
  • 2
    http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Achrome May 19 '13 at 13:27
  • 1
    Dont use eval, use (new Function(strCode))() , check out what Jay Garcia and the team at ModusCreate put out in the link above : http://moduscreate.com/javascript-performance-tips-tricks/ Why? performance. – Jason May 19 '13 at 13:44
1

You can use eval for this.

enter image description here

Don't pass any data from a remote server to eval before validating it. Damage can be done with eval.

Jordan Doyle
  • 2,976
  • 4
  • 22
  • 38
1

You could do this besides eval:

function run(myoperation) {
    return new Function('return ' + myoperation + ';').call();
}

run('2+2'); // return 4
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Pass the string to eval() function.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
0

you can use Function

var result = new Function("return " + "2+2")();
Anoop
  • 23,044
  • 10
  • 62
  • 76