JavaScript functions to escape and unescape HTML

by timvasil 12/28/2008 9:10:00 PM

JavaScript doesn't have built-in functions to escape or unescape HTML, which may come in handy for certain DOM manipulations or AJAX scripting.  Here are the custom functions I wrote to handle these tasks.  I've tested the implementation with both IE and Firefox.

var g_oHtmlEncodeElement;

function htmlEscape(text)
{
    g_oHtmlEncodeElement = g_oHtmlEncodeElement || document.createElement("div");
    g_oHtmlEncodeElement.innerText = g_oHtmlEncodeElement.textContent = text;
    return g_oHtmlEncodeElement.innerHTML;
}

function htmlUnescape(html)
{
    g_oHtmlEncodeElement = g_oHtmlEncodeElement || document.createElement("div");
    g_oHtmlEncodeElement.textContent = g_oHtmlEncodeElement.innerText = "";
    g_oHtmlEncodeElement.innerHTML = html;
    return g_oHtmlEncodeElement.innerText || g_oHtmlEncodeElement.textContent;
}

Tags:

JavaScript | AJAX | IE | Firefox

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Search

Calendar

«  May 2013  »
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Recent posts

Recent comments

Archive