Thursday, September 25, 2008

JavaScript HTMLEncode function

Found this neat trick on another blog (http://lunarmedia.com/blogs/lunarmedia_blog/archive/2006/10/23/120405.aspx) to escape characters for presentation in HTML:

function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

2 comments:

BAz said...

Nice method! Why re-invent the wheel i guess :)

Shlomi Rosenzweig said...

Thanks - solved a problem for me...