简体   繁体   中英

javascript: check whether expression is evaluatable or not?

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 ?

Catch the error:

try {
        eval(exp); 
    } catch (e) {
        if (e instanceof SyntaxError) {
            alert(e.message);
        }
    }

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 !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM