title: javascript regex replace html chars
body: <p>I'm using JavaScript to set the value of an input with text that may contain HTML specific chars such a <code>&amp;amp;</code> <code>&amp;nbsp;</code> etc.  So, I'm trying to find one regex that will match these values and replace them with the appropriate value ("&amp;", "&nbsp;") respectively, only I can't figure out the regex to do it.</p>
  
  <p>Here's my attempt:</p>
  
  <p>Make an object that contains the matches and reference to the replacement value:</p>
  
  <pre><code>var specialChars = {
    "&amp;amp;nbsp;" : " ",
    "&amp;amp;amp;"  : "&amp;",
    "&amp;amp;gt;"   : "&gt;",
    "&amp;amp;lt;"   : "&lt;"
  }
  </code></pre>
  
  <p>Then, I want to match my string</p>
  
  <pre><code>var stringToMatch = "This string has special chars &amp;amp;amp; and &amp;amp;nbsp;"
  </code></pre>
  
  <p>I tried something like</p>
  
  <pre><code>stringToMatch.replace(/(&amp;amp;nbsp;|&amp;amp;)/g,specialChars["$1"]);
  </code></pre>
  
  <p>but it doesn't work.  I don't really understand how to capture the special tag and replace it.  Any help is greatly appreciated.</p>