Decoding HTML Entities
HTML entities can be decoded by using several different methods involving vanilla JavaScript or JavaScript libraries. This guide will only go through vanilla JavaScript methods for decoding HTML entities as they are easy and straightforward.
Decoding HTML Entities with the <textarea> DOM Element
The first method is by using the textarea element. As the name suggests, the textarea element is used to create a simple text area where each character is interpreted as simple plain text.:
let txt = document.createElement("textarea");
txt.innerHTML = str;
return txt.value;
}
In the above code we first created the textarea element using the document.createElement() method. Then we wrote the string containing HTML entities inside the textarea using innerHTML property. This way the string will be converted to simple text and entities will be converted to characters. Lastly, we returned the string stored inside the txt variable which is the textarea.
Now if we call the decode function with an HTML entity as parameter it will return it as simple text:
let decodedStr = decode(encodedStr);
console.log(decodedStr);
Decoding HTML Entities with the DOMParser.parseFromString() method
The second method is by using the DOMParser.parseFromString() method. The DOMParser.parseFromString() method takes a string containing HTML and returns it as an HTML element:
let txt = new DOMParser().parseFromString(str, "text/html");
return txt.documentElement.textContent;
}
In the above code we first passed the string as an argument to the DOMParser.parseFromString() method and got it back as an HTML element by specifying the second argument as “text/html”. We then returned the text content of the newly created HTML element.
Now calling the decode() function:
let decodedStr = decode(encodedStr);
console.log(decodedStr);
Conclusion
HTML Entities are necessary for proper viewing of text on webpages. Some websites contain code snippets as simple text. Without Entities it would be difficult to differentiate between what is a HTML code for the webpage and what is just plain text.