I need to evaluate user-entered arithmetic expressions like “2 * (3 + 4)” in Javascript but I don’t want to use eval for security reasons.
I could strip out all the characters that are not numbers or operators but I’m not sure this would be safe anyway and it would be nice if the user could use functions like cos, sqrt, etc…
Are there any Javascript libraries that do arithmetic expression evaluation?
You can try JavaScript Expression Evaluator:
Then your code will be like that:
The source code is on GitHub and it’s published on npm as
expr-eval. Can be used like so: