| by Arround The Web | No comments

How to Decode HTML Entities Using JavaScript

HTML stores its reserved characters as character entities. Character entities are simple text strings that start with an & and end with a ;. HTML entities are necessary because if you’re trying to write HTML’s special characters like < or > as simple text then HTML should be able to somehow store them so that they are not interpreted as HTML code. HTML entities are necessary for proper viewing of rendering of text on webpages. Entities can also be used when trying to write characters which are generally not found on standard keyboards.

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.:

function decode(str) {

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 encodedStr = "&lt;p&gt;";

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:

function decode(str) {

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 encodedStr = "&lt;p&gt;";

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.

Share Button

Source: linuxhint.com

Leave a Reply