title: Replace words in a string, but ignore HTML
body: <p>I'm trying to write a highlight plugin, and would like to preserve HTML formatting. Is it possible to ignore all the characters between &lt; and > in a string when doing a replace using javascript?</p>
  
  <p>Using the following as an example:</p>
  
  <pre><code>var string = "Lorem ipsum dolor span sit amet, consectetuer &lt;span class='dolor'&gt;dolor&lt;/span&gt; adipiscing elit.";
  </code></pre>
  
  <p>I would like to be able to achieve the following (replace 'dolor' with 'FOO'):</p>
  
  <pre><code>var string = "Lorem ipsum FOO span sit amet, consectetuer &lt;span class='dolor'&gt;FOO&lt;/span&gt; adipiscing elit.";
  </code></pre>
  
  <p>Or perhaps even this (replace 'span' with 'BAR'):</p>
  
  <pre><code>var string = "Lorem ipsum dolor BAR sit amet, consectetuer &lt;span class='dolor'&gt;dolor&lt;/span&gt; adipiscing elit.";
  </code></pre>
  
  <p>I came very close to finding an answer given by tambler here: <a href="https://stackoverflow.com/questions/2289552/jquery-can-you-ignore-html-in-string-while-doing-a-replace">Can you ignore HTML in a string while doing a Replace with jQuery?</a> but, for some reason, I just can't get the accepted answer to work.</p>
  
  <p>I'm completely new to regex, so any help would be gratefully appreciated.</p>