My htmlspecialchars() functions for Javascript

December 22nd, 2007 Leave a comment Go to comments

I thought I'd post my htmlspecialchars() functions for Javascript.  This should mimic the PHP version of htmlspecialchars().  I also include rhtmlspecialchars() in case you need to do the reverse.


function htmlspecialchars(str) {
 if (typeof(str) == "string") {
  str = str.replace(/&/g, "&"); /* must do & first */
  str = str.replace(/"/g, """);
  str = str.replace(/'/g, "'");
  str = str.replace(/</g, "&lt;");
  str = str.replace(/>/g, "&gt;");
  }
 return str;
 }
function rhtmlspecialchars(str) {
 if (typeof(str) == "string") {
  str = str.replace(/&gt;/ig, ">");
  str = str.replace(/&lt;/ig, "<");
  str = str.replace(/&#039;/g, "'");
  str = str.replace(/&quot;/ig, '"');
  str = str.replace(/&amp;/ig, '&'); /* must do &amp; last */
  }
 return str;
 }

 
  1. ty
    September 24th, 2010 at 21:54 | #1

    you rock, works great!
     

Allowed HTML: <b>, <i>, <em>, <strong>. All other < and > will be replaced with &lt; and &gt;.