Entity encoding and decoding with jQuery

May 11, 2014, 6:22 pm
Author: James Griffiths

In both examples of encoding and decoding HTML entities we are going to assume your text is referenced by a variable named textContent - although you can call it anything you like.

Encoding HTML entities

var textContent = $("").text(textContent).html();

The above code snippet sets the innerText of a temporary element, which is not assigned to the page DOM, (in this case we use a textarea, to avoid potential XSS attacks), and then, using the text() method, encode the content which is subsequently pulled back out of the temporary textarea element with the html() method.

Decoding HTML entities

var textContent = $("").html(textContent).text();

The above code snippet sets the innerHTML of a temporary element, which is not assigned to the page DOM, (in this case we use a textarea, to avoid potential XSS attacks), and then, using the html() method, decode the content into HTML which is subsequently pulled back out of the temporary textarea element with the text() method.

If you've been having problems parsing HTML entities via JavaScript then the above snippets should help to resolve those issues.

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.