The five characters that matter

Escaping these five is enough for HTML text and attribute contexts. It is not enough for JavaScript strings inside a script tag, CSS, or URLs — each context has its own escaping rules.

CharacterEntityWhere it breaks
&&Starts an entity; must always be escaped
<&lt;Starts a tag
>&gt;Ends a tag
"&quot;Attribute values in double quotes
'&#39;Attribute values in single quotes

Named vs numeric entities

&amp; is a named entity; &#38; is its numeric equivalent. Browsers understand both. Named entities cover a few thousand characters (mostly typography and symbols); numeric references can encode any Unicode code point, including emoji via surrogate pairs.

HTML5 recognizes a long list of named entities without semicolons, which is a legacy quirk. Always write the semicolon; without it, &amp can be parsed differently depending on context.

Decoding entities safely

Decoding turns &lt;script&gt; into <script>. That is useful for reading encoded content, but it also means decoding untrusted input can reintroduce markup. If you plan to display the decoded text, escape it again or insert it with textContent, never innerHTML.

  • Use textContent for untrusted text.
  • Use a sanitizer such as DOMPurify if HTML is genuinely required.
  • Never decode entities and then concatenate into an HTML string.