Five characters do the damage
Browsers treat < as the start of a tag and & as the start of an entity, and quotes end an attribute value. Encoding replaces those with references, so they display and are never interpreted:
& → &
< → <
> → >
" → "
' → '
Single quotes use the numeric form because ' was missing from HTML 4, and some older software still does not recognize it. The & must always be handled first or in one pass, or the ampersands in the newly created references would be encoded a second time.
Numeric and hexadecimal modes
Both modes write the Unicode code point of the five special characters and of everything outside basic ASCII. The letter é becomes é or é. An emoji is a single code point even though JavaScript stores it as two units, so 😀 becomes 😀 and not a pair of broken halves.
These forms are handy when a file’s encoding is uncertain, as with an old email template, since the output is pure ASCII and survives any character set.
Double encoding
If you see &lt; on a page, or a literal < where a < belongs, the text has been encoded twice. Decode removes exactly one layer, so &lt; becomes <. Press it again on the result for the next layer. Unknown names such as &foo; stay as written so nothing is silently lost.
Context decides the right escaping
HTML encoding is correct for text between tags and for quoted attribute values. Other positions follow other rules:
- Inside a URL parameter, use percent-encoding. The URL Encoder on this site does that.
- Inside a script block, use JSON encoding and keep the data out of the markup where you can.
- An href still needs its scheme checked, because javascript:alert(1) contains nothing that HTML encoding would change.
In application code, rely on your template engine’s automatic escaping, such as Blade’s double braces, React’s JSX or Django templates. Manual escaping is easy to forget in one place, and one place is enough for a cross-site scripting bug.