![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements