Convert HTML to Plain Text for Comparison

How HTML-to-text conversion works, what it keeps or drops, how to choose an extraction method, and how to normalize output so diffs show only real changes.

Comparing two HTML documents directly usually produces noisy results. A changed class name, a reordered attribute, or a paragraph wrapped in a new div shows up as a difference even when the words a reader sees are identical. Converting both versions to plain text before comparing removes most of that markup noise so the diff shows changes in content. This guide explains what the conversion changes, how the main approaches differ, and where the output may not be usable as expected.

What HTML-to-text conversion actually changes

An HTML to text converter replaces a structured document with a sequence of characters. Tags, attributes, styles and scripts are removed or used only as hints for where line breaks go. Character references such as & or   are usually decoded into the characters they stand for. The result keeps the words but loses most of the information about how those words were presented or what role they played.

The conversion is lossy and one-way. You cannot rebuild the original HTML from the plain text, because headings, emphasis, link targets, table structure and attributes are gone. That is the point for comparison work, but it also means the text should be treated as a comparison artifact, not a replacement for the source.

Several presentation effects are easy to mistake for changes in the text itself. How a converter handles them determines whether two versions compare as equal:

  • CSS case changes: a rule such as text-transform: uppercase changes how text looks, not the stored characters. Source-based extraction keeps the original case; rendered-text extraction may output the transformed case.
  • Hidden content: text styled with display: none or marked hidden is still in the source. Source-based extraction includes it; rendered-text extraction normally omits it.
  • Visual mirroring and rotation: a CSS transform that flips text horizontally changes only its appearance. The underlying characters, and therefore the extracted text, stay the same. This differs from character-order reversal, which actually rearranges the stored characters and would show up as a real difference.
  • Bidirectional display: right-to-left text is stored in logical (reading) order and reordered only for display. The dir attribute is lost in conversion, so plain text may look different in a viewer that guesses direction differently, but the stored character order, which is what a diff compares, is unchanged. Explicit Unicode bidi control characters, if present in the source, remain as invisible characters and can cause differences you cannot see.
  • Unicode styled characters: "bold" or "script" letters produced by substituting mathematical alphanumeric symbols are distinct code points, not formatting. They survive conversion and will not match ordinary letters unless you apply compatibility normalization (NFKC), which maps many of them back to their base letters.
  • Images: alt text lives in an attribute, so many extractors drop it. If alt text changes matter to your comparison, choose or configure a method that includes it.

Choosing an extraction approach

Most tools fall into one of four approaches. The right one depends on whether you want to compare what the source contains or what a visitor sees.

Approach | What it reads | Hidden content | CSS case changes | Line breaks and structure | Stability for diffs
Regex or naive tag stripping | Raw markup with tags deleted by pattern | Included | Ignored (original case kept) | Often lost; paragraphs can run together | Fragile; breaks on comments, scripts, attributes containing angle brackets
Parser-based extraction | Parsed document tree, text nodes in source order | Included unless the tool removes it | Ignored (original case kept) | Depends on whether the tool inserts breaks for block elements | Good; does not depend on CSS or layout
Rendered-text extraction (browser-style visible text) | The page as laid out with its styles applied | Usually omitted | May be applied | Follows visual blocks | Good for visible content, but output can change when stylesheets change
Text-mode rendering (terminal-browser style output) | A rendered page formatted for fixed-width display | Usually omitted | Varies by tool | Adds wrapping, indentation, sometimes link numbering | Wrapping can create false differences unless disabled or normalized

The following matched input shows how the approaches can diverge. The outputs are illustrative of typical behavior for each approach, not observed results from a specific tool. A slash marks a line break.

<p>Price: <b>$20</b>&nbsp;per&nbsp;month</p>
<p style="display:none">Old price: $25</p>
<p style="text-transform:uppercase">limited offer</p>
Approach | Illustrative output
Naive tag stripping without entity decoding | Price: $20 per month Old price: $25 limited offer
Parser-based extraction with block-aware breaks | Price: $20 per month / Old price: $25 / limited offer
Rendered-text extraction | Price: $20 per month / LIMITED OFFER

Both of the last two outputs are valid, but they answer different questions. If an editor deleted the hidden paragraph, the parser-based comparison would flag it and the rendered comparison would not. If a stylesheet stopped uppercasing the offer, the rendered comparison might flag it and the parser-based one would not.

  • Comparing content revisions, such as CMS drafts, exported documents or templates: use parser-based extraction. It tracks what was written regardless of styling.
  • Checking what visitors actually see on a live page: use rendered-text extraction, and compare pages loaded under the same conditions (same stylesheet version, viewport and logged-in state).
  • Quick checks on small, simple, trusted snippets: tag stripping can be acceptable, but decode entities and check the output by eye.
  • Reviewing differences in a terminal or plain-text email workflow: text-mode rendering is readable, but turn off or normalize line wrapping before diffing.

Normalizing the output so formatting differences are ignored

Even after conversion, invisible or near-identical characters can produce differences that are not meaningful. Applying the same normalization to both sides before diffing removes most of them. Decide each step deliberately, because every rule you add also hides a class of real changes.

  • Collapse runs of spaces and tabs, and trim each line. Source HTML indentation is not content.
  • Replace non-breaking spaces with ordinary spaces if spacing type does not matter to you.
  • Remove soft hyphens, zero-width spaces, word joiners and byte order marks, which are invisible but distinct characters.
  • Apply Unicode NFC normalization so precomposed and decomposed accented letters compare as equal. Use NFKC only if you also want styled letters, ligatures and full-width forms folded to their base characters.
  • Optionally standardize curly and straight quotes or dash variants, if typographic changes are not part of what you are reviewing.
  • Drop empty lines, or collapse them to one, so wrapper elements do not create false differences.

Leave zero-width joiner and zero-width non-joiner alone unless you are sure they are noise. They are required for some emoji sequences and for correct spelling in several scripts, including Persian, so removing them can change meaning.

The sketch below shows parser-based extraction followed by normalization, using only the Python standard library. It is an illustrative starting point and has not been tested against a specific document set for this article; check its output on your own files before relying on it.

from html.parser import HTMLParser
import re
import unicodedata

class TextExtractor(HTMLParser):
    SKIP = {"script", "style", "template", "noscript"}
    BLOCK = {"p", "div", "li", "tr", "br", "table", "ul", "ol",
             "h1", "h2", "h3", "h4", "h5", "h6", "section", "article"}

    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.parts = []
        self.skip_depth = 0

    def handle_starttag(self, tag, attrs):
        if tag in self.SKIP:
            self.skip_depth += 1
        elif tag in self.BLOCK:
            self.parts.append("\n")
        elif tag == "img" and not self.skip_depth:
            alt = dict(attrs).get("alt")
            if alt:
                self.parts.append(f"[image: {alt}]")

    def handle_endtag(self, tag):
        if tag in self.SKIP and self.skip_depth:
            self.skip_depth -= 1
        elif tag in self.BLOCK:
            self.parts.append("\n")

    def handle_data(self, data):
        if not self.skip_depth:
            self.parts.append(data)

def normalize(text):
    text = unicodedata.normalize("NFC", text)
    text = text.replace("\u00a0", " ").replace("\u00ad", "")
    text = re.sub(r"[\u200b\u2060\ufeff]", "", text)
    lines = [re.sub(r"[ \t]+", " ", line).strip() for line in text.split("\n")]
    return "\n".join(line for line in lines if line)

def html_to_comparable_text(markup):
    parser = TextExtractor()
    parser.feed(markup)
    parser.close()
    return normalize("".join(parser.parts))

This sketch keeps hidden elements, because it does not evaluate CSS, and records image alt text in brackets so alt changes appear in the diff. Remove the image branch if you want alt text ignored. Run the output of both versions through any line-based diff tool.

Will the converted text be readable and usable where you need it?

Plain text transfers more predictably than HTML, but a few limits affect whether it does the job.

  • Lost meaning from structure: tables flatten into lines, so a value moving between columns may look unchanged or may look like an unrelated edit. If table data matters, consider exporting tables separately, for example as tab- or comma-separated rows.
  • Lost link targets: plain text keeps link wording but not the destination. If changed link targets matter, use or configure a converter that appends the target after the link text.
  • Accessibility information: plain text drops heading levels, list semantics and landmark roles that assistive technology relies on. A plain-text comparison cannot tell you whether a page's accessibility changed; review the HTML or an accessibility tree for that.
  • Copy and paste: many applications put both an HTML version and a plain-text version on the clipboard, and the destination decides which one it uses. Copying from a browser and pasting into a diff tool may therefore give rendered text, including CSS case changes and omitting hidden content. Paste into a plain-text editor first if you need to see exactly what was transferred.
  • Invisible characters: non-breaking spaces, zero-width characters and bidi controls survive copy and paste and are invisible in most editors. If a diff flags a line that looks identical, inspect it with a tool that shows code points.
  • Line endings and encoding: make sure both files use the same encoding, preferably UTF-8, and the same line-ending style, or every line can appear changed.

Sensitive content needs one more check. Online converters and comparison sites receive whatever you paste or upload, and you generally cannot verify how long it is stored or who can access it. For contracts, unpublished pages, customer data or internal documents, prefer a converter that runs locally, such as a script, a desktop diff tool or a browser's own developer features, and read the service's data-handling terms before using a hosted one.

Gaps in this guide

No tool-specific documentation or test results were available for this article, so it does not state that any particular converter or website produces the outputs shown. The comparison tables describe typical behavior for each approach and are labeled illustrative. Before adopting a tool, run your own matched samples through it, including hidden elements, entities, tables and right-to-left text, and confirm that its output matches the kind of comparison you need.