If I have an arithmetic expression as a string (“2+3*4/5”), is there a way to get this computed with the JavaScript Math object without parsing that entire string to separate everything out?
Edit: For now, I’m just concerned about supporting +-*/ with order of operations. I’m open to eval if we can piece together a regular expression to address security.
You could use some regex parsing to check that there’s nothing evil in the string, then just
eval.With just simple arithmetic operations, a safe regex would be:
Note this won’t validate that the expression is balanced in terms of operands and operators (i.e. it would okay “+2*”), but it will stop any weird code injections.