Skip to content
Amal Hashim
All posts
Snippet

jQuery HTML encode and decode

Two small functions that encode and decode HTML characters by letting jQuery and the browser do the work.

1 min read#JavaScript#jQuery

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>');
// "&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;"

htmlDecode('&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;');
// "<b>Tom & Jerry</b>"