title: highlight words in html using regex & javascript - almost there
body: <p>I am writing a jquery plugin that will do a browser-style find-on-page search.  I need to improve the search, but don't want to get into parsing the html quite yet.  </p>
  
  <p>At the moment my approach is to take an entire DOM element and all nested elements and simply run a regex find/replace for a given term.  In the replace I will simply wrap a span around the matched term and use that span as my anchor to do highlighting, scrolling, etc. <strong>It is vital that no characters inside any html tags are matched.</strong></p>
  
  <p>This is as close as I have gotten:</p>
  
  <pre><code>(?&lt;=^|&gt;)([^&gt;&lt;].*?)(?=&lt;|$)
  </code></pre>
  
  <p>It does a very good job of capturing all characters that are <strong>not</strong> in an html tag, but I'm having trouble figuring out how to insert my search term.</p>
  
  <pre><code>Input: Any html element (this could be quite large, eg &lt;body&gt;)    
  Search Term: 1 or more characters    
  Replace Txt: &lt;span class='highlight'&gt;$1&lt;/span&gt;
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The following regex does what I want when I'm testing with <a href="http://gskinner.com/RegExr/" rel="nofollow">http://gskinner.com/RegExr/</a>...</p>
  
  <pre><code>Regex: (?&lt;=^|&gt;)(.*?)(SEARCH_STRING)(?=.*?&lt;|$)
  Replacement: $1&lt;span class='highlight'&gt;$2&lt;/span&gt;
  </code></pre>
  
  <p>However I am having some trouble using it in my javascript.  With the following code chrome is giving me the error "Invalid regular expression: /(?&lt;=^|>)(.<em>?)(Mary)(?=.</em>?&lt;|$)/: Invalid group".</p>
  
  <pre><code>var origText = $('#'+opt.targetElements).data('origText');
  var regx = new RegExp("(?&lt;=^|&gt;)(.*?)(" + $this.val() + ")(?=.*?&lt;|$)", 'gi');
  $('#'+opt.targetElements).each(function() {
     var text = origText.replace(regx, '$1&lt;span class="' + opt.resultClass + '"&gt;$2&lt;/span&gt;');
     $(this).html(text);
  });
  </code></pre>
  
  <p>It's breaking on the group (?&lt;=^|>) - is this something clumsy or a difference in the Regex engines?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The reason this regex is breaking on that group is because Javascript does not support regex lookbehinds.  For reference &amp; possible solutions: <a href="http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript" rel="nofollow">http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript</a>.</p>