Strip HTML from a given text

Parse HTML in an inert document and return its text.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

strip-html-from-a-given-text.js
function stripHtml(html) { return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''; }

Usage

usage.js
stripHtml('<p>Your order <strong>8812</strong> has shipped.</p>'); // → 'Your order 8812 has shipped.'
stripHtml('<img src=x onerror="steal()">Hi'); // → 'Hi'

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

Know the limits

  • DOMParser builds an inert document: scripts do not run and images do not load, so the second line is safe. The result is text; never insert the original HTML into the page.
  • textContent drops link addresses and paragraph breaks. That suits previews and search snippets; for an email’s text/plain alternative, use an HTML-to-text converter that keeps URLs and line breaks.
  • Browser only. In Node.js, use an HTML parser library.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Strip HTML from a given text from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Inert-parsing and text-only limits documented. Executed in Chromium. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.