irishwill200 irishwill200 - 1 month ago 7
jQuery Question

Replace all occurences of ('content') from first bracket - ( to VERY last )?

I have a string that may be:

Hello (hiii(1998 overhill) hpp) there
.
I want to strip to remove the brackets and content from within but keeping the words
Hello there
.

Below is my code but it removes the first part:
(hiii(1998 overhill)
leaving
hpp)
behind.

myString = "Hello (hiii(1998 overhill) hpp) there";
myString = myString.replace(/ \([^)]*\)/g, '');


With that said, i want it to do this for all occurrences which is why i supplied the
/g
but how do i do it for the last occurrence of (content) hi) also? For future reference.

So if i have
"Hello (ddd(dog) kk) and hello (pineapple(g)"
is it possible to cut out the last bracket so im left with:
Hello (ddd(dog) kk) and hello
removing the
(pineapple(g)
?

Thanks!

Answer

I found two ways of possible situations you want.

One of them is the one that I told you in the comment:

var myString = 'Hello (ddd(dog) kk) and hello (pineapple(g)';
console.log(myString.replace(/\(.+\)/g, ''));

This one will remove from the first ( to the last ).


Or removing pairs of brackets contents recursively:

function removeBracketsContents(str) {
  while (str.indexOf('(') > -1 & str.indexOf(')') > -1) {
    str = str.replace(/\([^\(\)]+\)/g, '');
  }
  return str;
}

console.log(removeBracketsContents('Hello (hiii(1998 overhill) hpp) there'));
console.log(removeBracketsContents('Hello (ddd(dog) kk) and hello (pineapple(g))'));