title: Javascript, Use a regex to replace content outside of HTML tags only
body: <p>I am trying to write a regular expression in JavaScript to replace strings that are outside of HTML tags, and to ignore the strings within HTML tags.</p>
  
  <p>Here's my JavaScript code:</p>
  
  <pre><code>var content = "Hi, my &lt;span user="John"&gt;name&lt;/span&gt; is &amp;nbsp;John";
  var user = 'John';
  var regex = new RegExp('(&amp;nbsp;)?' + user,'g');
  content.replace(regex, function($0,$1){
      return $1 ? $0 : '&lt;img src="images/user.png"&gt;';
  });
  </code></pre>
  
  <p>My regex is <code>"(&amp;nbsp;)?John"</code>.</p>
  
  <p>The pattern works the way I want to, but it applies the matching to tag data, which I don't want.</p>
  
  <p>So, the idea is to ignore everything between tags: <code>&lt;</code> and <code>&gt;</code>, and to ignore: <code>&amp;nbsp;John</code>.</p>
  
  <p>Can it be done?</p>