Remove Nested Patterns with One Line of JavaScript
Steven Levithan has been flagrant by creating a simple way to remove nested patterns with a while loop and a replace:
JAVASCRIPT:
-
-
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 not allowed in the inner pattern) with an empty string. This repeats from the inside out, until the regex no longer matches. At that point, the result of the replacement is the same as the subject string, and the loop ends.
You can use a similar approach to grab nested patterns rather than delete them, as shown below.
JAVASCRIPT:
-
-
var str = “abc(d(e())f)(gh)ijk()”,
-
re = /\([^()]*\)/,
-
output = [],
-
match, parts, last;
-
-
while (match = re.exec(str)) {
-
parts = match[0].split(“\uFFFF”);
-
if (parts.length <2)
-
last = output.push(match[0]) - 1;
-
else
-
output[last] = parts[0] + output[last] + parts[1];
-
str = str.replace(re, “\uFFFF”);
-
}
-
-
// output -> ["(d(e())f)", "(gh)", "()"]
-





