W3docs

How to Strip HTML from a String in JavaScript

In this tutorial, you will find several approaches to strippingan HTML from a sting in JavaScript easily. Get the codes and explanations right away.

In the scope of this tutorial, we are going to show two approaches to stripping an HTML from a string in JavaScript.

The function can execute inline JavaScript codes:

JavaScript strip HTML from a string

javascript— editable

If you are running in a browser, it is best to use DOMParser:

JavaScript strip HTML from a string

function strip(html) {
  let doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

Unlike the div.innerHTML approach, DOMParser does not request external resources (such as images) during parsing.

Warning

Both solutions work only in the browser.

DOMParser

The DOMParser interface allows parsing XML or HTML source code from a string into a DOM Document. XMLHttpRequest parses XML and HTML directly from a URL-addressable resource and returns a Document in its response property.