WEB MARKUP GUIDE · 6 MIN READ
HTML entities: when to encode and when to decode
HTML uses characters such as angle brackets and ampersands as markup. When those characters should appear as visible text, they need an unambiguous representation. An entity reference begins with an ampersand and ends with a semicolon, such as < for a visible less-than sign.
The five common characters
Text placed into HTML commonly encodes ampersand, less-than, greater-than, double quote and single quote. Context matters: text inside an element and text inside an attribute are parsed differently. Use a trusted context-aware template or framework for application output rather than assembling HTML strings manually.
Named and numeric references
A named entity such as & is memorable. A decimal numeric reference such as & and a hexadecimal reference such as & can represent the same ampersand. The HTML Entity Encoder and Decoder handles the common named set plus decimal and hexadecimal references for small inspection tasks.
Encoding is not sanitising
Encoding a value for one HTML context can prevent it from being interpreted as markup there. Sanitising is a broader policy that decides which elements, attributes and URLs are allowed in an HTML document. If users can supply rich text, use a maintained HTML sanitizer and a restrictive allow-list. The Strip HTML Tags tool creates plain text but is not a security policy for rendering untrusted markup.
Avoid double encoding
If < is encoded again, the ampersand becomes &lt;, and the page may display the entity text rather than the intended character. Track whether a value is raw text, encoded text or parsed markup. Decode only when you trust the destination and actually need the original character representation.
Practical debugging steps
- Identify the output context: text node, attribute, URL, CSS or JavaScript.
- Inspect the raw source rather than only the rendered page.
- Encode once at the output boundary.
- Do not decode and render untrusted content.
- Test quotes, ampersands and angle brackets as edge cases.
HTML entity FAQ
Is Base64 an HTML escaping method?
No. Base64 is a reversible data representation and does not make untrusted HTML safe to render.
Why does an entity appear literally on the page?
It may have been double encoded or inserted into a context that does not parse HTML entities.