Why HTML Syntax Trees Beat Regular Expressions

A tested comparison: a common regex "fix" for HTML misses attacks and corrupts text, while a syntax tree handles every case.

Every codebase that touches HTML seems to grow a helper like this one, usually written under time pressure to strip event handlers from user content:

JS
const naive = (html) => html.replace(/\s+on\w+="[^"]*"/gi, '')

It looks reasonable and it passes the first test anyone writes. We ran it against four inputs next to rehype-sanitize, which works on a parsed syntax tree.

The experiment

regex-vs-tree.mjs
import {rehype} from 'rehype'
import rehypeSanitize from 'rehype-sanitize'

const inputs = [
  '<img src="x" onerror="alert(1)">', // quoted: the regex catches it
  '<img src=x onerror=alert(1)>', // unquoted: the regex misses it
  "<a href='#' onclick='alert(1)'>x</a>", // single quotes: missed
  '<p>Docs: the onclick="handler()" attribute runs code.</p>' // prose: mangled
]

// A typical "quick fix" seen in real codebases:
const naive = (html) => html.replace(/\s+on\w+="[^"]*"/gi, '')

for (const html of inputs) {
  const tree = String(await rehype().data('settings', {fragment: true}).use(rehypeSanitize).process(html))
  console.log('input: ' + html)
  console.log('regex: ' + naive(html))
  console.log('tree:  ' + tree)
  console.log()
}

Here is the actual output:

Output node regex-vs-tree.mjs
input: <img src="x" onerror="alert(1)">
regex: <img src="x">
tree:  <img src="x">

input: <img src=x onerror=alert(1)>
regex: <img src=x onerror=alert(1)>
tree:  <img src="x">

input: <a href='#' onclick='alert(1)'>x</a>
regex: <a href='#' onclick='alert(1)'>x</a>
tree:  <a href="#">x</a>

input: <p>Docs: the onclick="handler()" attribute runs code.</p>
regex: <p>Docs: the attribute runs code.</p>
tree:  <p>Docs: the onclick="handler()" attribute runs code.</p>

What went wrong

1. It works only for the syntax you thought of

The regex expects double quotes. HTML also allows single quotes and, for many values, no quotes at all. The second and third inputs are just as valid as the first, and the regex leaves both event handlers intact. You can extend the pattern, and then there are tabs and newlines between attributes, entity-encoded characters, uppercase names, attributes without spaces before them after a quoted value… Each fix adds complexity and still trails the full grammar.

2. It cannot tell markup from text

The fourth input is documentation about the onclick attribute. The text onclick="handler()" is prose inside a paragraph, not an attribute. The regex cannot know that, so it silently deletes part of the sentence. The syntax tree knows it is a text node and leaves it alone.

3. It ignores how browsers actually parse

Browsers do not reject bad HTML; they repair it using precise, standardized rules. Unclosed tags, stray quotes and misnested elements are all turned into a definite structure. An attacker only needs one input where your regex sees one thing and the browser builds another. A parser that implements the WHATWG algorithm, as rehype-parse does through parse5, builds the same structure the browser will.

What the tree approach does differently

rehype first turns the string into a tree of elements, attributes and text, using the browser's rules. Then rehype-sanitize walks that tree and keeps only what an allowlist permits. Quoting style is irrelevant, because quotes are gone after parsing: an attribute is just a property on an element node. Text is never mistaken for markup, because it is a different node type. Finally, the tree is serialized with consistent, correct escaping.

The same reasoning applies beyond security: adding ids to headings, rewriting links, removing empty paragraphs, extracting text. Anything you would do with a regex over HTML is more robust as a small tree transformation. Writing one usually takes fewer lines than a regex with all its fixes.

When a regex is fine

Regular expressions are perfect for text that is not HTML, and for quick, one-off searches through files you control, where a missed match costs nothing. The moment the input is untrusted, or the output is published, parse it.

Try it

Paste your own tricky markup into the HTML Sanitizer to see what a tree-based allowlist removes, or into the HTML Formatter to see how a browser would repair it.

Sources and further reading

Use ↑ ↓ to move, Enter to open.