Removing parentheses from mathematical expressions in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of mathematical expressions, str, as the first and the only argument.

The task of our function is to remove parentheses from the expression keeping the operations and operands in place.

For example, if the input to the function is −

Input

const str = 'u-(v-w-(x+y))-z';

Output

const output = 'u-v+w+x+y-z';

Example

Following is the code −

 Live Demo

const str = 'u-(v-w-(x+y))-z';
const removeParentheses = (str = '') => {
   let stack = []
   let lastSign = '+'
      for (let char of str) {
         if (char === '(' || char === ')') {
            lastSign = stack[stack.length - 1] || '+'
         } else if (char === '+') {
            if (stack[stack.length - 1] !== '-' && stack[stack.length - 1] !== '+') {
               stack.push(lastSign)
            }
         } else if (char === '-') {
            if (lastSign === '-') {
               if (stack[stack.length - 1] === '-') stack.pop()
                  stack.push('+')
         } else {
            if (stack[stack.length - 1] === '+') stack.pop()
            stack.push('-')
            }
         } else {
            stack.push(char)
      }
   }
   return stack.join('').replace(/^\+/, '')
};
console.log(removeParentheses(str));

Output

u-v+w+x+y-z

Updated on: 22-Apr-2021

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements