title: Fastest method to escape HTML tags as HTML entities?
body: <p>I'm writing a Chrome extension that involves doing a <strong>lot</strong> of the following job: sanitizing strings that <em>might</em> contain HTML tags, by converting <code>&lt;</code>, <code>&gt;</code> and <code>&amp;</code> to <code>&amp;lt;</code>, <code>&amp;gt;</code> and <code>&amp;amp;</code>, respectively.</p>
  
  <p>(In other words, the same as PHP's <code>htmlspecialchars(str, ENT_NOQUOTES)</code> – I don't think there's any real need to convert double-quote characters.)</p>
  
  <p>This is the fastest function I have found so far:</p>
  
  <pre><code>function safe_tags(str) {
      return str.replace(/&amp;/g,'&amp;amp;').replace(/&lt;/g,'&amp;lt;').replace(/&gt;/g,'&amp;gt;') ;
  }
  </code></pre>
  
  <p>But there's still a big lag when I have to run a few thousand strings through it in one go. </p>
  
  <p>Can anyone improve on this? It's mostly for strings between 10 and 150 characters, if that makes a difference. </p>
  
  <p>(One idea I had was not to bother encoding the greater-than sign – would there be any real danger with that?)</p>