Strip HTML from a given text
Parse HTML in an inert document and return its text.
function stripHtml(html) { return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''; }
Usage
stripHtml('<p>Your order <strong>8812</strong> has shipped.</p>'); // → 'Your order 8812 has shipped.'
stripHtml('<img src=x onerror="steal()">Hi'); // → 'Hi'
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.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.