HTML escaping

You can make the browser do all your HTML escaping:

function escape(text) {

var div = document.createElement('div');

div.innerText = text;

return div.innerHTML;

}

But the equivalent unescaping doesn't always work:

function unescape(html) {

var div = document.createElement('div');

div.innerHTML = html;

return div.innerText;

}

The issue with the unescaping is that if you give legitimate HTML like '<script>alert("hi");</script>', the script tags are considered elements and the innerText will just return alert("hi");

That said, we can hack it (and I haven't tested this extensively), but just doing a replace of the left bracket first:

function unescape(html) {

var div = document.createElement('div');

div.innerHTML = html.replace(/</g, '&lt;');

return div.innerText;

}

The normal way to do HTML escaping is to just have a set of things to replace in the string. See http://code.google.com/p/jslibs/wiki/JavascriptTips#Escape_and_unescape_HTML_entities for a very extensive example.