July 6, 2006 - 10:38 UTC - Tags: javascript jquery escaping
You may sometimes need to unescape HTML escaped strings in javascript. I found a neat trick to do this using the browser internal escaping.
This entry in the blog
ecmanaut presents a neat way to unescape HTML without calling homebrewed methods replacing each character. Using this I created the following javascript function:
function unescapeHTML(html) {
var htmlNode = document.createElement("DIV");
htmlNode.innerHTML = html;
if(htmlNode.innerText !== undefined)
return htmlNode.innerText; // IE
return htmlNode.textContent; // FF
}
Update 2007-07-07: Added HG's version which should work properly in both IE and FF
Update: Adding Marcus Phillips suggestion for testing against undefined
jQuery versions for both ways
Update 2010-04-28:function unescapeHTML(html) {
return $("<div />").html(html).text();
}
function escapeHTML(html) {
return $("<div />").text(html).html();
}
Comments closed for this post