JavaScript: How to decode and encode HTML entities

Vit Tertiumnon
Nov 22, 2018

--

JavaScript has no methods to encode and decode HTML entities, so you can use these functions.

Decode HTML-entities

function decodeHTMLEntities(text) {
var textArea = document.createElement('textarea');
textArea.innerHTML = text;
return textArea.value;
}

Decode HTML-entities (JQuery)

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

Encode HTML-entities

function encodeHTMLEntities(text) {
var textArea = document.createElement('textarea');
textArea.innerText = text;
return textArea.innerHTML;
}

Encode HTML-entities (JQuery)

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

--

--