How to Convert HTML Strings to Plain Text in JavaScript?

Estimated read time 1 min read

To convert an HTML string to plain text in JavaScript, you can use the textContent property of an HTML element. The textContent property returns the text content of an element and all its descendants, excluding any HTML tags. Here’s an example:

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

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.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply