decodeHTML.js
Decode HTML entities from an encoded string.
Example
// Returns "<p>In this course, you'll learn:</p>"
let decoded = decodeHTML('<p>In this course, you&rsquo;ll learn:</p>');
The helper function
/**
* Decode HTML entities from an encoded string
* https://stackoverflow.com/a/7394787/1293256
* @param {String} html The encoded HTML string
* @return {String} A decoded HTML string
*/
function decodeHTML (html) {
let txt = document.createElement('textarea');
txt.innerHTML = html;
return txt.value;
}
How it works
It works by creating a <textarea>
element and injecting your encoded HTML into it. The browser automatically converts that back into proper HTML. You can then grab the value
from the <textarea>
, and like magic, you have decided HTML.