1

I have a string and I want to iterate the .replace(re,'') until I achieve and empty sting "". How to do this rather than repeating over and over again the same method

var isValid = (s)=> {
   const re = /(\(\))|(\[\])|(\{\})/gi
   return s.replace(re,'').replace(re,'').replace(re,'').replace(re,'') !='' ? false :true
  
};

console.log(isValid("[({(())}[()])]"))
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Ade N
  • 145
  • 1
  • 1
  • 12
  • Would [replaceAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) help here? – evolutionxbox Jan 04 '21 at 14:12
  • To rephrase (if I'm not mistaken) you want to **recursively replace/remove** brackets that have a ***"valid"*** closing bracket? – Roko C. Buljan Jan 04 '21 at 14:12
  • @Roko C. Buljan exactly. – Ade N Jan 04 '21 at 14:26
  • There are many posts online that discuss solving this type of problem. Just Google for "balanced parentheses algorithm". Most of them use a stack to do this. Here is an SO question that discusses this: https://stackoverflow.com/questions/16874176/parenthesis-brackets-matching-using-stack-algorithm. – Francis Gagnon Jan 04 '21 at 14:41
  • Note that the stack approach solves this in O(n) instead of your O(n^2). – Francis Gagnon Jan 04 '21 at 15:05

1 Answers1

1

You can use a while loop.

var isValid = (s)=> {
   const re = /(\(\))|(\[\])|(\{\})/gi
   while(re.test(s)) s = s.replace(re, '');
   return s === '';
};
Unmitigated
  • 76,500
  • 11
  • 62
  • 80