Web Development. Client Satisfaction. Web Consultancy. Professional. UX. Fast. Responsive Design. Dynamic. Interactive. Innovative. Ecommerce. Wordpress plugins. Prestashop modules. You name it.

How to decode HTML characters in variable

How to decode HTML characters in variable

Let's say you get some JSON response back and it has a lot of HTML characters. You need to decode HTML characters to normal text in order to append the new value to front end.

The following JSON response is an example of html characters you could recieve from php.

{
    "message": "We're unable to complete your request at this time."
}

 

One of my favourite methods to decode these types of characters is the following function because is very easy to use, and every time when you need to convert a string which contain HTML characters you can just call the function with your string passed as parameter, then the function will return the string without html characters (decoded to normal text).

 

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

 

 

As you can see in the above function first we create a "textarea" element in a variable and then append our string to the textarea to be read as html and then we just return the value from textarea. Anyway there are a lot of methods to decode these types of responses, I can not show all functions because there are many but I can show you a few more.

function htmlDecode(value) {
  return $("<textarea/>").html(value).text();
}

function htmlEncode(value) {
  return $('<textarea/>').text(value).html();
}

 

The next one will deal with &#xxxx styled HTML characters:

var decodeHtmlEntity = function(str) {
  return str.replace(/&#(\d+);/g, function(match, dec) {
    return String.fromCharCode(dec);
  });
};

var encodeHtmlEntity = function(str) {
  var buf = [];
  for (var i=str.length-1;i>=0;i--) {
    buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
  }
  return buf.join('');
};

var entity = '&#39640;&#32423;&#31243;&#24207;&#35774;&#35745;';
var str = '高级程序设计';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);

 

Leave a Reply

avatar
  Subscribe  
Notify of