black_yurizan black_yurizan - 1 month ago 6
Javascript Question

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

I have a string expression like this

10/3*4-7
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

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');
console.log(answer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.6.0/math.min.js"></script>