HTML to Text Converter
Heading A paragraph with bold text & an entity.
The HTML to text converter removes tags and decodes entities, with an option to keep paragraph breaks or collapse everything to one line. Script and style blocks are removed with their contents, which a plain tag-stripping regex does not do. It leaves the JavaScript behind as text.
How it works
- Script, style and comment blocks are removed entirely, contents included.
- When keeping structure, closing tags for block elements become paragraph breaks and <br> becomes a single newline.
- All remaining tags are removed.
- Named entities such as & and are decoded, then numeric entities in both decimal and hexadecimal form.
- Whitespace is collapsed. Runs of spaces become one, and runs of blank lines become one blank line.
Entity decoding runs after tag removal deliberately. Doing it first would turn <script> into a real script tag, which the tag stripper would then remove, silently deleting text that was meant to be visible.
Examples
Keeping paragraph structure
HTML
<h1>Heading</h1> <p>A paragraph with <strong>bold</strong> text & an entity.</p>
Result
Heading A paragraph with bold text & an entity.
The closing h1 and p tags become paragraph breaks, inline tags vanish without adding space, and & decodes to an ampersand.
Script content is removed, not exposed
HTML
<p>Visible</p><script>alert("hidden")</script>Result
Visible
A regex that only removes tags would leave alert("hidden") behind as visible text. Script and style blocks are removed with their contents first.
Frequently asked questions
Why does it remove script contents rather than just the tags?
Because stripping only the tags leaves the JavaScript behind as body text, which is the single most common bug in hand-rolled HTML strippers. Script and style blocks are removed with their contents before any other processing.
Which HTML entities are decoded?
The 16 named entities that appear in real content, ampersand, angle brackets, quotes, non-breaking space, dashes, ellipsis, copyright, currency symbols, plus all numeric entities in both decimal and hexadecimal form. The full named-entity list runs to over 2,000, nearly all of which never appear in practice.
Why is the entity decoding done after the tags are removed?
Because doing it first would convert <script> into an actual script tag, which the tag stripper would then delete along with the text it contained. Order matters, and getting it backwards silently loses content.
Does it preserve links?
No. The href is discarded and only the link text survives. Plain text has nowhere to put a URL without inventing a convention, and the two common conventions, footnotes and inline parentheses, both change the reading of the text.