What Are HTML Entities and When Do You Need Them?

htmlencoding

Some characters have special meaning in HTML, such as < and &. An HTML entity lets you write those characters literally so a browser displays them instead of interpreting them as markup.

Why entities exist

If you write <b> as text, the browser treats it as a tag. Writing &lt;b&gt; instead shows the literal characters. Entities also provide a way to write non-ASCII characters as numeric codes.

Named versus numeric

  • Named entities are readable, such as &lt;, &gt; and &amp;.
  • Numeric entities use a code point, such as &#60; or &#x3C;.

Escaping in code

JavaScript:

function escapeHtml(value) {
  return value.replace(/[&<>"']/g, c => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
  }[c]))
}

Python:

import html
print(html.escape('<b> & "quotes"'))

PHP:

echo htmlspecialchars('<b> & "quotes"', ENT_QUOTES);

Common pitfalls

  • Encoding twice, which turns &lt; into &amp;lt;.
  • Decoding untrusted text and then inserting it into HTML without sanitizing.
  • Forgetting that named entity support varies outside the common set.

Frequently asked questions

  • Should I encode everything? Encode when text will be inserted into HTML; it is unnecessary in plain text contexts.
  • Is my text uploaded? No. Encoding and decoding can run locally in your browser.

Need to escape or unescape HTML? Try the free HTML Entity Encoder / Decoder — it runs locally.