Skip to content

How to Strip HTML from a String in JavaScript

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

Output appears here after Run.

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

JavaScript strip HTML from a string

javascript
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.

Dual-run preview — compare with live Symfony routes.