nextwebgen.com

The Next Generation Web Now

Remove Nested Patterns with One Line of JavaScript

Filed under: Web 2.0 News — Dion Almaer at 8:36 am on Friday, May 30, 2008

Steven Levithan has been flagrant by creating a simple way to remove nested patterns with a while loop and a replace:

JAVASCRIPT:

  1.  
  2. var str = “abc&lt;1&lt;2<>3>4>def”;
  3.  
  4. while (str != (str = str.replace(/<[^<>]*>/g, “”)));
  5.  
  6. // str -> "abcdef"
  7.  

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:

  1.  
  2. var str = “abc(d(e())f)(gh)ijk()”,
  3.     re = /\([^()]*\)/,
  4.     output = [],
  5.     match, parts, last;
  6.  
  7. while (match = re.exec(str)) {
  8.     parts = match[0].split(\uFFFF”);
  9.     if (parts.length <2)
  10.         last = output.push(match[0]) - 1;
  11.     else
  12.         output[last] = parts[0] + output[last] + parts[1];
  13.     str = str.replace(re, \uFFFF”);
  14. }
  15.  
  16. // output -> ["(d(e())f)", "(gh)", "()"]
  17.  
Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blogmarks
  • del.icio.us
  • De.lirio.us
  • digg
  • NewsVine
  • YahooMyWeb

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>