2.7 — Character Escaping & Entities
To display the very symbols that define HTML’s own syntax – like <, >, &, and quotes – you must learn to escape them. This is not a workaround; it’s a fundamental part of the parser’s design. Without escaping, your page can break or even become invisible.
The Parser’s Trigger Characters
As the browser reads your HTML, it’s like a train switching tracks. Certain characters instantly throw a switch and change the parser’s behaviour. Watch the animation below to see how <, >, &, and quotes trigger different states.
<) → Tag Open → (encounters >) → Data
When the parser sees & in data, it switches into a character reference mode, expecting a named entity or numeric code. Quotes (" and ') delimit attribute values; a stray quote inside a value prematurely ends the attribute and corrupts the markup.
The Five Reserved Characters & Their Escapes
To print these characters as visible text, you must replace them with one of three character reference systems:
- Named entities – human‑readable codes like
<for<. - Decimal numeric references – base‑10 Unicode codepoint:
<for<. - Hexadecimal numeric references – base‑16 codepoint:
<for<.
| Character | Named Entity | Decimal | Hex |
|---|---|---|---|
< | < | < | < |
> | > | > | > |
& | & | & | & |
" | " | " | " |
' | ' | ' | ' |
Rule: All references start with & and end with ;. Named entities are case‑sensitive.
Where Escaping Is Required – Context Matters
The parser’s sensitivity changes depending on where you are inside the document:
- Normal text (body): Always escape
<and&. They will otherwise start a new tag or reference. - Attribute values: Always escape
&. Escape quotes ("or') only if they match the outer delimiter. - Raw text elements (
<script>,<style>): Character references are ignored – they appear literally. So don’t use them inside scripts. - Escapable raw text elements (
<textarea>,<title>): Character references are expanded, so you can safely use entities.
Practical Examples – See the Difference
Example 1: Escaping in Normal Text
Verify that a && b are evaluated < 100
The parser sees an unterminated tag – layout breaks!Verify that a && b are evaluated < 100
In the corrected version, the ampersands become & and the less‑than sign becomes <. The browser renders "&&" and "<" without misinterpreting them as code.
Example 2: Escaping Quotes Inside an Attribute
<input value="He said "hello"">
"<input value="He said "hello"">
Here the inner quotes are replaced by ", keeping the attribute’s boundaries intact.
Character escaping is the bridge between HTML’s syntax and the text you want to display. The five reserved characters – <, >, &, ", ' – must be replaced by their entity references in data and attribute values. Remember that context changes the rules: inside raw text elements, entities don’t work. With these techniques, your markup stays valid, your content stays safe, and every character appears exactly as intended.