04 · Browser & Web Platform
easycodingjavascript~6 min

Escape HTML Safely

Objective: Understand output encoding as the primary XSS defense.

Implement `escapeHtml(input)` so user text can be placed inside HTML text or a quoted attribute without becoming markup.

  • Escape & < > " and '.
  • Escape & first (or in a single pass) so entities are not double-escaped.
  • Coerce non-strings with String().
JavaScript

⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • Why is escaping not enough inside a <script> block or an href?
  • How does a Content-Security-Policy limit the damage of a missed escape?
  • When is textContent better than building HTML strings?