Monday, September 22, 2014

Decode HTML Entities

This post is nothing special. Just a note to myself.

I needed a basic javascript function to decode HTML entities in a string. The string that is retrieved from the database was being encoded in the jsp with the HTML entity '&' encoded in the string. 

So the string 'Tom & Harry' is being shown as "Tom & Harry'.

I wrote a basic HTML decoder function in javascript since the strings are coming from a trusted source (my database).

Here is the HTML decoder function.

function decodeHTMLEntities(str) {
 var textArea = document.createElement("textarea");
 textArea.innerHTML = str; 
 return textArea.value;

If the source of the data is not trusted, you may use some of the other HTML decoder options discussed in the following links.

HTML decode options 1
HTML decode options 2

Please take note that the discussions from these links advise against using jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM.

HTML Entity Reference
HTML Entitiy Reference

No comments:

Post a Comment