Skip to main content Accessibility Feedback

decodeHTML.js

Decode HTML entities from an encoded string.

Source Code

Example

// Returns "<p>In this course, you'll learn:</p>"
let decoded = decodeHTML('&lt;p&gt;In this course, you&amp;rsquo;ll learn:&lt;/p&gt;');

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.


Find this useful? You can support my work by purchasing an annual membership.