Contact Us

 Nirav     Feb,08 2017

Decode HTML Code with jQuery

In one of the project, we are storing all form fields in json string format (i.e. {"name":"myname", "email":"may@xyz.com", "address":"myaddressdetail"}) in the database table. To avoid the JSON parsing error due to any special characters while retrieving data from database and deserialize the json string, I convert all special characters in the fields value with their HTML-escaped equivalents (by using coldfusion HTMLEditFormat() function). Till this it's works fine but I found the issue with the HTML-escaped equivalents code when I am going to retrieve data with AJAX and placed value to appropriate input field. At here I want to convert the HTML-escaped equivalents code to appropriate special character (i.e. & needs to be converted into & sign).

I have start searching for the solution, but most are suggest me to use the regular expression to convert '&' to '&' and for all other HTML-escaped equivalents code. But I need to write regular expression for each HTML-escaped equivalents code and I don't want to do that. After some googling I got the tricky solution with the jQuery .text() function. I made one javascript function HTMLDecode as follows:

function HTMLDecode(s){return jQuery('<div></div>').html(s).text();}

In this function, I pass the string value as argument from which I need to convert all HTML-escaped equivalents code to their special character. To do this I just create the one jQuery object of div and set the string value to the div inner html with .html() jQuery function. Finally, I used the jQuery .text() function which used to get the text contents of the element. 

For example if I pass the string 'test detail &amp; test', the HTMLDecode function will return 'test detail & test'. I think this is more better way than the use of the regular expression to decode HTML code.