Demystifying HTML Entities: Escaping Special Characters and Preventing XSS
By Evorenza Engineering • Category: Security & Privacy
Reserved Characters in HTML
HTML relies on specific syntactic delimiters such as the less-than sign (<) and greater-than sign (>) to define element tags, and the ampersand (&) to initiate character references. When user-supplied text contains these reserved characters without proper escaping, the browser parser interprets them as markup instructions rather than literal strings.
This failure to distinguish code from data is the root cause of Cross-Site Scripting (XSS) vulnerabilities.
The Core Five XML/HTML Entities
Every developer should memorize the five essential entities:
- Ampersand (&) encodes to &
- Less-than (<) encodes to <
- Greater-than (>) encodes to >
- Double quote (") encodes to "
- Single quote (') encodes to ' or '
When to Use Named vs Numeric Entities
- Named Entities: Easier for human developers to read and maintain (©, €, —). However, legacy XML parsers only recognize the core five unless an explicit DTD is supplied.
- Numeric Entities (Decimal/Hex): Universally valid across all XML, XHTML, and HTML5 parsers without external entity declaration requirements.