FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Escape HTML for Safe Text

Escape HTML for Safe Text

easy
By FrontendAtlas Editorial · Updated Jul 14, 2026
Implement escapeHtml(text) to encode &, <, >, " and ' when raw text must be interpolated into the HTML text-content portion of a constructed markup string. For live DOM text, assign textContent instead. This narrow encoder is not a sanitizer and does not make values safe for URLs, event handlers, style/CSS, unquoted attributes, or other output contexts.

Arguments

  • text: string — Raw user text to escape for HTML.

Returns

string — A string encoded for the HTML text-content context in constructed markup.
Examples
escapeHtml('<div class="x">Tom & Jerry's</div>')
// => "&lt;div class=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/div&gt;"

escapeHtml('5 > 3 & 2 < 4')
// => "5 &gt; 3 &amp; 2 &lt; 4"

Solution

Overview

This encoder converts five characters into HTML entities so a raw value is treated as text when interpolated into the text-content portion of a constructed HTML string. Prefer assigning Element.textContent when writing text into a live DOM node because it avoids parsing markup at all. Output encoding is context-specific: this function is not URL validation, a markup sanitizer, or safe handling for event-handler, style/CSS, unquoted-attribute, or arbitrary attribute contexts.

1

Approach 1: Regex + lookup map (preferred)

Create a map for the five characters and replace them with a single regex pass. Use the result only as HTML text content inside a constructed markup string; for a live DOM node, prefer textContent. Complexity is O(n) time and O(n) space.

export default function escapeHtml(text) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };
  return String(text).replace(/[&<>"']/g, (ch) => map[ch]);
}
export default function escapeHtml(text: string): string {
  const map: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };
  return String(text).replace(/[&<>"']/g, (ch) => map[ch]);
}
2

Approach 2: Chained replace (simple but order-sensitive)

You can chain replace calls, but you must escape & first or you will double-escape the entities you create later.

export default function escapeHtml(text) {
  return String(text)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
export default function escapeHtml(text: string): string {
  return String(text)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

Notes & Pitfalls

Pitfalls
  • Escaping is context-specific. This HTML-text encoder does not make strings safe for URLs, event handlers, JavaScript, style/CSS, unquoted attributes, or arbitrary attribute contexts.
  • If you chain replacements, escape `&` first or you will double-escape entities.
  • Escaping does not allow rich HTML; use a well-maintained sanitizer with an allowlist when you must accept markup.
  • For live DOM text, assign `textContent` instead of constructing an HTML string.
Edge cases
  • Empty string should return an empty string.
  • Already-escaped input will be escaped again (expected for raw-text encoding).
  • Quotes are encoded too, but that does not broaden this exercise beyond the documented HTML text-content context.
Techniques
  • Regex replacement with a lookup table.
  • String normalization via String(text).
  • Context-aware output encoding.

Common mistakes on this challenge

  • escapeHtml replacement map or order is incorrect

    Escaping should map all HTML special chars, including `&` before entity-like sequences.

    • Convert input to string and replace ampersand, angle brackets, double quote, and apostrophe.
    • Ensure ampersands are escaped before other substitutions, even in existing entity-like text.
    • Leave text without escapable chars unchanged.
    • Use this encoder only for the documented HTML text-content context; live DOM text should use `textContent`.

Resources

  • OWASP – XSS Prevention Cheat Sheet
  • MDN – Element.textContent

Similar questions

Sanitize href URL (Block javascript: XSS)intermediateSafe JSON Parse (Fallback on Error)easyValidate Username (Rules + Edge Cases)easy

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
51 / 88Next →→