blog.craiga.id.au — htmlspecialchars in JavaScript

Simple function for HTML-encoding characters (i.e. transforming characters such as <, > and & into HTML entities):

function htmlspecialchars(s)
{
    var temp = document.createElement('div');
    temp.appendChild(document.createTextNode(s));
    return temp.innerHTML;
}

Inspired by the PHP function of the same name.

Published: Friday, 24th October 2008 at 11:07 AM

Related

About Craig Anderson

By day, he works for ABC TV as a web dev­el­oper. By night, he plays bass gui­tar in Look Who's Tox­ic. He also runs a little Unix Time­stamp con­ver­sion site. There are plen­ty of other things he should be doing, but most of the time he's dreaming of what he'll do when he grows up while watching bad Star Trek spin-offs.