Evaluating a string as a mathematical expression in JavaScript

We are required to write a JavaScript function that takes in a stringified mathematical equation. The function should return the result of the equation provided to the function.

For example: If the equation is ?

const str = '1+23+4+5-30';

Then the output should be 3

Example

The code for this will be ?

const str = '1+23+4+5-30';
const compute = (str = '') => {
   let total = 0;
   str = str.match(/[+\-]*(\.\d+|\d+(\.\d+)?)/g) || [];
   while (str.length) {
      total += parseFloat(str.shift());
   };
   return total;
};
console.log(compute(str));

Output

And the output in the console will be ?

3

How It Works

The function uses a regular expression /[+\-]*(\.\d+|\d+(\.\d+)?)/g to extract all numbers with their signs from the string. The regex matches:

  • [+\-]* - Optional plus or minus signs
  • (\.\d+|\d+(\.\d+)?) - Numbers (including decimals)

Each matched number is converted using parseFloat() and added to the total.

Alternative Approach Using eval()

For simple expressions, you can use eval(), though it's not recommended for user input due to security risks:

const str = '1+23+4+5-30';
const result = eval(str);
console.log(result);
3

Conclusion

The regex approach safely evaluates mathematical expressions by parsing numbers and operators. Avoid eval() with untrusted input for security reasons.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements