Home > Back-end >  Remove contents between parentheses in Javascript
Remove contents between parentheses in Javascript

Time:10-27

Create a function that accepts a string as input, removes all content between parentheses, and returns the modified string. If the amount of left and right parentheses doesn't match, return empty string

I have to create a function that removes all content between parentheses and returns the string without it.

For example, this input 12(3(45))67(8)9 will return this output 12679.

If the number of parentheses isn't correct return an empty string.

This is my approach:

function removeContent(str) {
  let leftP = 0, rightP = 0;
  // wrong number of parentheses scenario
  for( let i = 0; i < str.length; i  ) {
    if(str[i] === '(' ) leftP  ;
    if(str[i] === ')' ) rightP  ;
  }
  if( leftP !== rightP) return "";
  
  // remove the content otherwise
}

console.log(removeContent('12(3(45))67(8)9'));

Don't know how to do the combination between pairing parentheses and remove the content.

CodePudding user response:

An easy way to do this is to keep track of bracket count, and then output letters only when the bracket count is equal to 0.

At the end, if the bracket count is not zero, you can also tell it to return the empty string as requested..

eg..

function removeContent(string) {
  let bracketCount = 0;
  let output = '';
  for (const letter of string) {
    if (letter === '(') bracketCount  = 1
    else if (letter === ')') bracketCount -= 1
    else if (bracketCount === 0) output  = letter;
  }
  return bracketCount === 0 ? output : '';
}


console.log(removeContent('12(3(45))67(8)9'));
console.log(removeContent('12(345))67(8)9'));
console.log(removeContent('1(2)(3)45(7)8(((9)))77'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

do a find replace with regular expression /\( [\d\(]*\) /g

  • Related