Categories
JavaScript Answers

How to strip HTML from text with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *