Reputation: 727
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 ?
Upvotes: 3
Views: 796
Reputation: 64
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 !!
Upvotes: -1
Reputation: 1804
Catch the error:
try {
eval(exp);
} catch (e) {
if (e instanceof SyntaxError) {
alert(e.message);
}
}
Upvotes: 4