HTML Sanitizer
Problem statement
Implement sanitizeHTML(input), a simplified HTML sanitizer inspired by the platform HTML Sanitizer API.
Parse the HTML into a detached DOM tree, sanitize it, and return the resulting HTML string.
The sanitizer should
- Remove these element subtrees entirely:
script,iframe,object,embed. - Remove all HTML comment nodes.
- Remove any attribute whose name starts with
on. - Remove
hrefandsrcattributes whose trimmed, case-insensitive value starts withjavascript:. - Preserve all other parsed HTML.
Example
sanitizeHTML('<p>Hello <strong>world</strong></p>');
// '<p>Hello <strong>world</strong></p>'
This question is intentionally scoped to normal browser HTML. You do not need SVG, MathML, CSS sanitization, Trusted Types, or spec-perfect URL normalization.
Requirements & constraints
- Run in a browser DOM environment.
- Remove dangerous element subtrees entirely.
- Strip event handler attributes and `javascript:` URLs.
How to approach HTML Sanitizer
The strategy an interviewer expects you to reach for.
HTML sanitization is XSS defense: untrusted markup must become safe DOM before it touches the page. Naive move element.innerHTML = userString or regex-strip <script>. Regex loses to malformed tags and event handlers. Where it breaks onerror attributes, javascript: URLs, comments with payloads, and nested dangerous tags survive naive filters. The fix Parse into a detached <template>, walk the tree, drop blocked tags (script/iframe/…), strip dangerous attrs, keep a safe allowlist. Never insert until clean. Remember: Parse → walk → allowlist. Regex is not a sanitizer. Say this in the interview: I'd parse untrusted HTML in a template element, remove blocked tags and dangerous attributes on a tree walk, and only then insert the cleaned nodes.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.