How to Convert HTML Characters to Text Using JavaScript?

Estimated read time 2 min read

To convert HTML characters to text in JavaScript, you can use the textContent property of an HTML element or the innerText property. The textContent property returns the text content of an element and all its descendants, excluding any HTML tags. The innerText property returns the text content of an element, including the text of all its descendants, but excluding the text of any hidden elements and the text of elements that are not rendered. Here’s an example using textContent:

var htmlString = "Hello, <strong>World</strong>!";
var tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlString;
var plainText = tempDiv.textContent;
console.log(plainText); // "Hello, <strong>World</strong>!"

In this example, the HTML string is assigned to the innerHTML property of a temporary div element. The textContent property of the tempDiv element is then used to extract the plain text, which is stored in the plainText variable. The plain text can then be used as needed.

This approach uses the innerHTML property to parse the HTML string and the textContent property to extract the text content, so it is able to handle any valid HTML string and return its plain text representation, including HTML characters.

Here’s an example using innerText:

var htmlString = "Hello, <strong>World</strong>!";
var tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlString;
var plainText = tempDiv.innerText;
console.log(plainText); // "Hello, World!"

In this example, the HTML string is assigned to the innerHTML property of a temporary div element. The innerText property of the tempDiv element is then used to extract the plain text, which is stored in the plainText variable. The plain text can then be used as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply