Sometimes, we want to strip HTML from text with JavaScript
In this article, we’ll look at how to strip HTML from text with JavaScript.
How to strip HTML from text with JavaScript?
To strip HTML from text with JavaScript, we call parseFromString
to parse the HTML string.
Then we get its text content.
For instance, we write
const strip = (html) => {
const doc = new DOMParser().parseFromString(html, "text/html");
return doc.body.textContent || "";
};
to define the strip
function.
In it, we call parseFromString
to parse the html
string into a DOM object.
Then we get the text from the DOM object with textContent
.
Conclusion
To strip HTML from text with JavaScript, we call parseFromString
to parse the HTML string.
Then we get its text content.