- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Evaluating a mathematical expression considering Operator Precedence in JavaScript
- Evaluate a boolean expression represented as string in C++
- Java Program to parse a mathematical expression and operators
- Computing zeroes (solutions) of a mathematical equation in JavaScript
- Program to evaluate s-expression as string in Python
- Write a Regular Expression to remove all special characters from a JavaScript String?
- How to pass a lambda expression as a method parameter in Java?
- How to set a String as a key for an object - JavaScript?
- Ordering string as a number in a database?
- How to add a mathematical expression in axis label in a plot created by using plot function in R?
- How to match a regular expression against a string?
- Represent Int64 as a String in C#
- Represent Int32 as a String in C#
- How to write the comparator as a lambda expression in Java?
- How can we write Callable as a lambda expression in Java?

Advertisements