Escape HTML for Safe Text

easy
By FrontendAtlas Editorial · Updated Oct 10, 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.

Solution idea

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.

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"