In JavaScript, decoding and encoding HTML entities is a common task when dealing with user-generated content or manipulating strings. These functions can be used to encode and decode HTML entities as there is no built-in method in JavaScript. It’s essential for securing and properly displaying user input in web applications.
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();
}