Remove Nested Patterns with One Line of JavaScript
Wednesday, May 28th, 2008 • Related • Filed Under
Here's a neat little trick I came up with for removing nested patterns from a string.
var str = "abc<1<2<>3>4>def";
while (str != (str = str.replace(/<[^<>]*>/g, "")));
// str -> "abcdef"
Notice that the regex in this one-liner doesn't try to deal with nested patterns at all. The while loop's condition replaces instances of <…> (where angled brackets are [...]
