3

I have Random Expression which is given By users (Eg: 2+3*5,21*+(4)7,*-54+3). These Expression can contain any number of operand or operator to form a expression.I need to evaluate These Expression to get the Answer.I tried to evaluate using eval() function but Problem is when a wrong Expression is passed to eval() functions it throws a error and program halt.I tried it by

if(eval(exp))
{    
    //Action Expression is evaluatable
}
else
{
    //expression is not Evaluatable
}

but did not worked and produced error message

"SyntaxError: unterminated regular expression literal."  

Due to variety in expressions' nature it would be difficult for me to construct check statements before evaluating.
can you please suggest how can i simply check whether the expression passed to eval() function is correct or not ?

anand
  • 727
  • 11
  • 20
  • 2
    Try-catch the error? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch – XCS Jan 06 '15 at 17:34
  • Use `try`/`catch`, which is for dealing with thrown errors. `if`/`else` is for checking boolean conditions. – ajp15243 Jan 06 '15 at 17:36

2 Answers2

4

Catch the error:

try {
        eval(exp); 
    } catch (e) {
        if (e instanceof SyntaxError) {
            alert(e.message);
        }
    }
Inanda Menezes
  • 1,796
  • 13
  • 17
-1

You can try to put the content of your script in the "script" tag on the fly, and then check the return of the error function. Or define a variable at the end of your script and checks if it exists after the execution.

Or mayber you can find a response here : https://stackoverflow.com/a/9522483/2007701 !!

Community
  • 1
  • 1
Digix
  • 64
  • 4