How to solve the mathematical expression in a string?

Can anybody here help me in writing a function that takes in a string as an argument and solves the mathematical expression inside that string. And, it is assured that the string will have a pure mathematical expression (containing numbers 0-9 and operators +, - , *, / only) with no alphabets or special characters.

It’s way simpler than you imagine! JS provides a function called eval which takes a string as parameter and evaluates it and returns the result of evaluation.

function solveMathProblem(mathProblemString){
  return eval(mathProblemString);

solveMathProblem('(4*3)/2'); // 6

Having said that, I must mention that using eval can be unsafe. I won’t get into details of how and why. But know that using eval poses a lot of security threats.

I’d recommend you build your own function that will convert your string into tokens and then use a data structure like stack to evaluate the final result. This is a bit complicated than simply using eval. But it’s worth learning.

This link might help you understand how to use data structures to evaluate mathematical expressions.

1 Like