← JavaScript Coding

HTML Sanitizer

mediumdomsecurityxss
Asked at
Cloudflare
GitHub
Google
Meta
Shopify
Cloudflare, GitHub, Google, Meta, Shopify

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 href and src attributes whose trimmed, case-insensitive value starts with javascript:.
  • 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 &lt;script&gt;. 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 &lt;template&gt;, 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.

Premium

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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

4. Improve a function

JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Cloudflare interview
  • GitHub interview
  • Google interview
  • Meta interview
  • Shopify interview