Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

HTML concept: character-references

Character references let markup spell a character by name or code point, but the result depends on conforming syntax and the HTML tokenizer state.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

& | & | &

The named &, decimal numeric &, and hexadecimal numeric & references all produce &. Names are case-sensitive and the number denotes a code point; not every number is allowed, and invalid ranges follow parser replacement rules.

In conforming source a reference ends with a semicolon. For historical compatibility the parser recovers some names, so &copy can become ©, but omitting the semicolon is an error and can change longest matching relative to ©; never rely on recovery.

Attribute values have an additional historical exception: if a matched named reference lacks a semicolon and the next character is an ASCII alphanumeric or an equals sign, the match is not consumed. Thus &ampx and &amp=1 remain literal in an attribute, while &amp;=2 decodes the ampersand. Raw <script> and <style> content does not use character references as an escaping mechanism.

The example decodes &amp;, &#38;, &#x26;, legacy &copy, and complete &notin; in ordinary text; it also compares text &ampx and &amp=1 with literal attribute values &ampx and &amp=1. The terminated &amp;=2 decodes there, while raw style text preserves &amp;.

Examples

<!doctype html>
<meta charset="utf-8">
<output id="result"></output>
<script>
const markup = "<p id=text>&amp;|&#38;|&#x26;|&copy|&notin;|&ampx|&amp=1</p><p id=attr data-value=\"&ampx|&amp=1|&amp;=2\"></p><style id=raw>.x::before{content:\"&amp;\"}</style>";
const parsed = new DOMParser().parseFromString(markup, "text/html");
const textValue = parsed.querySelector("#text").textContent;
const attributeValue = parsed.querySelector("#attr").dataset.value;
const rawValue = parsed.querySelector("#raw").textContent;
result.textContent = `text=${textValue}; attribute=${attributeValue}; raw=${rawValue}`;
</script>

Result

text=&|&|&|©|∉|&x|&=1; attribute=&ampx|&amp=1|&=2; raw=.x::before{content:"&amp;"}

The executed example verifies named and numeric forms and the attribute-value-only exception when an ASCII alphanumeric or equals sign follows a semicolonless name.

Sources