title: Advanced JavaScript RegExp Replacement Within HTML tags
body: <p>I have javascript code that works pretty well like:</p>
  
  <pre><code>var rgx = /MyName/g;
  var curInnerHTML = document.body.innerHTML;
  curInnerHTML = curInnerHTML.replace(rgx, "&lt;span&gt;&lt;span class='myName'&gt;MyNameReplace&lt;/span&gt;&lt;/span&gt;");
  </code></pre>
  
  <p>The problem is that its matching the regex even in scenarios where it is contained within HTML attributes and what-not. How can I modify the regex so that it will <strong>only</strong> find it within the content of the HTML? For example, in this string</p>
  
  <pre><code>    &lt;div class="someclass" title="MyName"&gt;
  MyName
  &lt;/div&gt;
  </code></pre>
  
  <p>it currently results like (note the change in the title attribute):</p>
  
  <pre><code>        &lt;div class="someclass" title="&lt;span&gt;&lt;span class='myName'&gt;MyNameReplace&lt;/span&lt;/span&gt;"&gt;
  &lt;span&gt;&lt;span class='myName'&gt;
      MyNameReplace&lt;/span&gt;&lt;/span&gt;
      &lt;/div&gt;
  </code></pre>
  
  <p>But I need it to be (leave the title attribute untouched):</p>
  
  <pre><code>    &lt;div class="someclass" title="MyName"&gt;
  &lt;span&gt;&lt;span class='myName'&gt;MyNameReplace&lt;/span&gt;&lt;/span&gt;
  &lt;/div&gt;
  </code></pre>