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 can put the HTML in an element and then get the textContent
from the element.
For instance, we write
const stripHtml = (html) => {
const tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
};
to define the stripHtml
function that takes the html
string.
In it, we create a div with createElement
.
And then we assign html
to the tmp.innerHTML
to populate the div.
Then we get the plain text from the textContent
or innerText
properties.
Conclusion
To strip HTML from text with JavaScript, we can put the HTML in an element and then get the textContent
from the element.