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!
     

  2. JH
    April 22nd, 2011 at 23:14 | #2

    Excellent job. Thank you.
     

  3. Steve M
    April 22nd, 2013 at 20:16 | #3

    Thanks you sooooo much. Works great.  :)
     

If you would like a reply to your comment, you must leave your email address! We receive dozens of questions every month from people who don't leave us with any way to contact them, so we have no choice but to ignore the question. We try to reply to as many questions as we can, if we know the email address of the person who asked the question. Thanks in advance for writing in :)

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