jQuery HTML encode and decode
Two small functions that encode and decode HTML characters by letting jQuery and the browser do the work.
An easy way to encode or decode HTML characters is to use a temporary div. Setting .text() escapes the value, and reading .html() gives the encoded string. The decode function does the reverse.
js
function htmlEncode(value) {
return $('<div />').text(value).html();
}
function htmlDecode(value) {
return $('<div />').html(value).text();
}
Example
js
htmlEncode('<b>Tom & Jerry</b>');
// "<b>Tom & Jerry</b>"
htmlDecode('<b>Tom & Jerry</b>');
// "<b>Tom & Jerry</b>"