My htmlspecialchars() functions for Javascript

Posted in Javascript on December 22, 2007

0


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;
 }

 

Write a comment