Decode HTML Entities using Javascript

Tags: February 23, 2014 1:13 PM

I came into situation where I need to pass some string to Pen Editor instance. The problem is the string is already encoded to HTML entities by PHP's htmlentities(). So, when I have value like This is <strong>strong</strong> element. The Pen editor instance convert it into:

This is <strong>strong</strong> element

Instead of this:

This is strong element

The Solution

The solution is pretty dead simple just inject the string into textarea element and call the value property to get the content instead of innerHTML.

function decodeHtml(html){
  var txt = document.createElement("textarea");
  txt.innerHTML = html;
  return txt.value;
}
If your string already came from textarea like in my case then you don't event need to create a single function.

References

Share on Facebook Twitter

0 comments:

Post a Comment