Security · 4 min read
HTML Entities and Escaping: Preventing XSS
A handful of characters have special meaning in HTML, and displaying untrusted text without escaping them is the root of cross-site scripting (XSS) — one of the most common web vulnerabilities.
This guide explains HTML entities and why escaping is a security essential.
Try it yourself with the related tool.
Escape HTML entities →Advertisement
The characters that need escaping
In HTML, < and > delimit tags, & starts an entity, and quotes delimit attributes. To show these as literal text you replace them with entities: <, >, &, and ". Otherwise the browser interprets them as markup.
How escaping stops XSS
If a site drops untrusted input — a username, a comment — straight into a page and someone enters <script>, the browser runs it. Escaping turns that into harmless visible text (<script>) instead of a live tag. That single transformation neutralizes most reflected and stored XSS.
Named vs numeric entities
Named entities like © are readable; numeric entities like © reference a character by code point and work for anything, even characters without a name. Encoding all non-ASCII as numeric entities maximizes compatibility.
Escape at the right layer
Modern frameworks escape by default when you render text, which is why you should let them handle output rather than building HTML by hand. Understanding the mechanism helps you spot the places — like injecting raw HTML — where that protection is bypassed.
