Thursday, August 25, 2011

HTML Encoding & Decoding in JavaScript

It is easy to encode and decode HTML in server side code. When it comes to JavaScript there are many different way to do it. One simple way to achieve this is below.

Instead of relying on inbuilt function/method below code is using browser it self to encode and decode content. This way conversion between text is exactly same as browser renders.

Code simply create temporary DIV element and creates text node in this. This is same as rendering text in to DIV element. By doing this browser will encode the text added to DIV and then innerHTML will give encoded HTML. Do not forget to clean up temporary DIV from memory allocation point of view.

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

function decodeHTML (str)
{
var div = document.createElement('div');
div.innerHTML = str;
str = div.innerText;
div.removeNode();
return str;
}