black_yurizan black_yurizan - 1 year ago 108
Javascript Question

How do I convert string math expression to an actual math expression

I have a string expression like this

and I want to know if there is some type of javascript method that can convert the string into an actual expression so that I can get the answer . I have a function that randomly generates numbers and operators, and I want to get the result from the equation. However, the function that I created to get the result only does the calculation from left to right. It does not go by a operator priority, where * and / get calculated first and stuff like that. Is there something in javascript that can do that or would I have to create a function to do something like that?

Answer Source

I'd recommend using a library such as Math.js as this will parse the math expression using a regular expression. This will avoid opening the application up to Cross-site scripting (XSS) attacks.

var answer = math.eval('10/3*4-7');
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download