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!

5
  • 1
    What all operations can the string have? Commented May 19, 2013 at 13:22
  • 1
    eval, which is also evil. Commented May 19, 2013 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. Commented May 19, 2013 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. Commented May 19, 2013 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. Commented May 19, 2013 at 13:26

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

It can run any JavaScript code inputted. I'd say PHP's eval() is dangerous, but in JavaScript... whats the worst that could happen?
Dont use eval, use (new Function(strCode))() , check out what Jay Garcia and the team at ModusCreate put out in the link above : moduscreate.com/javascript-performance-tips-tricks Why? performance.
2

You could do this besides eval:

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

run('2+2'); // return 4

Comments

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.

Comments

0

Pass the string to eval() function.

Comments

0

you can use Function

var result = new Function("return " + "2+2")();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.