Possible Duplicate:
Safe evaluation of arithmetic expressions in Javascript
I am trying to build a online calculator as part of the website I have been working on.
I have + - * / ( ) AVG MIN MAX sine cos etc
as the operations. There are buttons for numbers, operators and functions. I just appending a string with whatever button is pressed.
I have to build a basic syntax checker on the UI side. The server will actually perform the operations and store them and display. I do not want to spend too much time writing the client side code but the idea is to validate to see it mathematically makes sense.
Here is my plan:
I will just try an eval()
of the string generated and catch the error. If the error is synatxError, then it means that the string is syntactically wrong. If it is any other type of error, I am okay with it.
So I did this at the beginning of the script:
Error.prototype.dummy_attribute = "notSyntaxError"
SyntaxError.prototype.dummy_attribute = "SyntaxError"
The above method does not work for me well because if there is string link 2()
I get a type error. Now I have to write a code that checks for empty brackets and brackets preceded by no operators, or brackets followed by no operators
Or Is there an alternative method I can use to check the syntax of the string I have to see if it mathematically makes sense.