Toolphy

HTML Escaping Explained: Entities and Safety

Last updated:

HTML gives a handful of characters special meaning: they mark up the page rather than displaying as text. If you want to show those characters rather than use them, you must escape them into entities. Get it wrong and a page either renders strangely or becomes a security hole.

Why escaping exists

The angle brackets < and > start and end tags. If a commenter types <b>hello</b>, the browser will make the text bold instead of showing the literal tag. Escaping converts the markup characters into codes the browser displays as plain text.

The core escape map

CharacterEntityWhy escape it
& (ampersand)&amp;Starts every entity; must be escaped first.
< (less than)&lt;Could start a tag.
> (greater than)&gt;Ends a tag.
" (quote)&quot;Ends an HTML attribute value.
' (apostrophe)&#39;Ends an attribute value using single quotes.

The ampersand comes first for a reason: if you escape it after the others, you would corrupt the very entities you just created, turning &lt; into &amp;lt;.

Named vs numeric entities

The same character can be written several ways:

All three refer to the same code point. Named entities are easier for humans; numeric forms work for any character, including emoji and rare symbols that have no name.

A before-and-after example

Raw text a user typed:

5 < 6 & 7 > 6 — she said "hi"

Escaped for safe display inside HTML:

5 &lt; 6 &amp; 7 &gt; 6 &mdash; she said &quot;hi&quot;

The browser shows the first line to the reader. The second line is what actually sits in the page source, so the symbols are displayed instead of being interpreted.

Context matters

Escaping is not one universal rule; it depends on where the text lands:

Using the wrong scheme for the context is a common source of bugs. An ampersand in a URL, for instance, should usually be %26, not &amp;.

Common mistakes

Going the other way

Decoding converts entities back into characters. It is useful when you copy text from page source and want the plain version, or when debugging why a page shows &amp; where you expected &. Paste the text into our HTML encoder / decoder to escape or unescape it in one step. If the content will end up in a data file, the CSV to JSON guide shows how special characters survive that conversion.

Try the HTML Encoder / Decoder →