How do I parse and evaluate a mathematical expression in a string (e.g. '1+1') without invoking eval(string) to yield its numerical value?
With that example, I want the function to accept '1+1' and return 2.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’ve eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):
I’m not sure if it’s faster than eval(), but as I have to carry out the operation lots of times I’m far more comfortable runing this script than creating loads of instances of the javascript compiler