How to Encode & Decode HTML Entities: Reserved Character Guide

To encode HTML entities, replace reserved syntax characters such as <, >, &, ", and ' with named or numeric character references (<, >, &, ", ') to prevent markup syntax corruption and Cross-Site Scripting (XSS). Decoding converts encoded references back into raw plain text characters using a client-side HTML Entity Extractor without server data transfer.
HyperText Markup Language (HTML) relies on specific syntax characters to construct elements, attributes, and structural boundaries across web documents. When raw content contains characters that overlap with HTML markup syntax—such as the less-than symbol (<) opening element tags or the ampersand (&) initiating entity references—browsers can misinterpret user text as executable code. Entity escaping converts reserved syntax symbols into safe, standardized sequences known as HTML entities.
Key Definitions: HTML Entity, Reserved Characters, Named References, Numeric References, and Contextual Escaping
Understanding HTML entity conversion requires precise definitions of core web encoding standards and browser parsing primitives:
- HTML Entity (Character Reference): A standardized sequence beginning with an ampersand (
&) and ending with a semicolon (;) representing reserved characters or Unicode code points. - Reserved Characters: Five structural characters—
<,>,&,", and'—with predefined syntactical meanings in W3C HTML specifications. - Named Character References: Standardized mnemonic aliases mapping entity strings to Unicode characters (for example,
©for©,<for<, and€for€). - Numeric Character References (NCR): Sequences referencing characters by Unicode code point values in decimal format (
&#NNN;, e.g.&for&) or hexadecimal format (&#xHHH;, e.g.&for&). - Contextual Escaping: Selecting character encoding rules based on the specific document execution context—such as HTML body, attributes, JavaScript, CSS, or URI parameters.
Why Reserved Characters Break HTML Documents (<, >, &, ", ')
HTML documents are parsed by web browsers using a formal state machine defined in W3C and WHATWG standards. Unescaped reserved characters trigger unintended state transitions during tokenization:
- Less-Than Symbol (
<): Triggers the Tag Open State. Browsers assume a new HTML element tag follows, corrupting body text and swallowing unclosed markup content. - Greater-Than Symbol (
>): Terminates element declarations in the Tag Name State or Attribute Value State, prematurely closing tags and dumping attributes into rendered text. - Ampersand (
&): Initiates the Character Reference State. Unescaped ampersands in URLs or text cause query string corruption or invalid entity parse errors. - Double Quote (
") and Single Quote ('): Delimit attribute boundaries. Unescaped quotes inside attribute values prematurely end the string, allowing attackers to inject new event attributes likeonload=.
Entity encoding ensures browser DOM parsers distinguish developer-defined document markup from user-supplied data strings.
Named Entities (&, <, >, ") vs Decimal (&) vs Hexadecimal (&) References
HTML supports three syntactical formats for entity references, resolving to identical Unicode code points in DOM trees:
1. Named Character References
Named entities use human-memorable aliases defined by HTML specifications (e.g., & for &, < for <, and " for "). HTML5 defines over 2,200 entities. However, unlisted Unicode characters lack named references.
2. Decimal Numeric Character References
Decimal references express characters using their base-10 Unicode code point index prefixed by &# and ended by ; (e.g. & for &, < for <). Decimal references cover the full Unicode standard without dictionary lookups.
3. Hexadecimal Numeric Character References
Hexadecimal references express characters using their base-16 Unicode code point value prefixed by &#x and ended by ; (e.g. & for &, < for <). Hexadecimal notation aligns directly with standard U+XXXX Unicode notation used in security filters.
| Entity Syntax Format | Prefix & Suffix | Example (Ampersand) | Unicode Coverage | Parsing Performance |
|---|---|---|---|---|
| Named Reference | &[name]; |
& |
Standard HTML5 catalog (~2,231 entities) | Requires dictionary lookup table |
| Decimal Reference | &#[decimal]; |
& |
Complete Unicode character set | Direct base-10 code point conversion |
| Hexadecimal Reference | &#x[hex]; |
& |
Complete Unicode character set | Direct base-16 code point conversion |
How Browsers Parse and Render HTML Entities in the DOM
Browsers process HTML entities during document parsing before constructing the Document Object Model (DOM) tree:
- HTML Tokenization Phase: The tokenizer reads byte streams sequentially. Encountering an ampersand (
&) enters the Character Reference State until a terminating semicolon is reached. - Entity Resolution: The parser maps named entity strings or numeric code point digits to a 32-bit Unicode scalar (e.g.
<resolves to U+003C). - DOM Text Node Creation: Decoded characters are stored as UTF-16 code units inside DOM Text Nodes. Reading
node.textContentreturns plain unencoded characters, whereasnode.innerHTMLre-serializes text back into HTML markup with entities. - CSSOM and Font Rendering: The layout engine matches decoded Unicode code points against CSSOM font rules to render visual glyph graphics.
Step-by-Step: How to Encode or Decode HTML Entities
Follow these five steps to encode reserved characters or decode entity-encoded text using EasyExtract’s client-side converter:
- Paste Input Code or Load HTML Document: Open the HTML Entity Extractor. Paste your target HTML string, database text snippet, or payload into the input area.
- Select Processing Operation (Encode vs Decode): Choose Encode to replace reserved characters with entity references, or Decode to convert entities back into readable plain text.
- Configure Entity Output Preference: Select Named Entities (
&), Decimal References (&), or Hexadecimal References (&). - Execute Client-Side Conversion Engine: The client-side parser executes instant memory string replacement without server network requests.
- Copy Decoded Text or Export Formatted Output: Copy the result to your clipboard or download the converted text file. To extract raw body text or structured tabular data from larger HTML files, use the dedicated HTML Text Extractor or HTML Table Extractor.
Common HTML Entities Reference Table
The table below lists primary reserved characters, typography symbols, currency icons, and structural entities:
| Character | Entity Name | Decimal Reference | Hexadecimal Reference | Purpose & Description |
|---|---|---|---|---|
< |
< |
< |
< |
Less-than symbol; prevents tag opening. |
> |
> |
> |
> |
Greater-than symbol; prevents tag termination breakout. |
& |
& |
& |
& |
Ampersand; prevents character reference ambiguity. |
" |
" |
" |
" |
Double quote; prevents attribute breakout. |
' |
' / ' |
' |
' |
Single quote; escapes attribute boundaries. |
(NBSP) |
|
  |
  |
Non-breaking space; prevents automated line wrapping. |
© |
© |
© |
© |
Copyright symbol for legal notices. |
® |
® |
® |
® |
Registered trademark symbol. |
™ |
™ |
™ |
™ |
Unregistered trademark symbol. |
€ |
€ |
€ |
€ |
Euro currency symbol. |
£ |
£ |
£ |
£ |
British Pound Sterling currency symbol. |
— |
— |
— |
— |
Em dash for sentence break typography. |
– |
– |
– |
– |
En dash for numerical range spans. |
Preventing Cross-Site Scripting (XSS) Attacks via Context-Aware HTML Entity Escaping
Cross-Site Scripting (XSS) occurs when untrusted input is injected into HTML documents without proper sanitisation, permitting malicious JavaScript execution. HTML entity encoding provides primary defense against Reflected and Stored XSS when applied with context awareness as defined in the OWASP XSS Prevention Cheat Sheet.
1. HTML Body Context Escaping
When inserting user input between element tags (e.g. <div>UNTRUSTED_DATA</div>), escaping reserved characters (<, >, &, ", ') neutralizes script injection. Converting <script> to <script> causes browsers to render safe text.
2. HTML Attribute Context Escaping
Inside attribute values (e.g. <input value="UNTRUSTED_DATA">), basic HTML entity encoding works if attributes are quoted. Unquoted attributes permit attackers to inject new event attributes like onload=. Attribute contexts require converting non-alphanumeric characters into numeric character references (&#xHH;).
3. Inline JavaScript, CSS, and URI Context Failures
Applying standard HTML entity escaping inside JavaScript blocks or URI parameters causes security failures. Inline scripts require Unicode escaping (e.g. \u0027), whereas URL parameters require percent-encoding (e.g. %20, %26).
HTML Entity Encoding in Modern Web Frameworks (React, Vue, Angular vs Raw Strings)
Modern frontend web frameworks provide automated contextual escaping to protect applications from XSS vulnerabilities:
React (JSX Auto-Escaping)
React automatically escapes string variables in JSX expressions (<div>{userInput}</div>). Rendering raw HTML requires dangerouslySetInnerHTML={{ __html: rawHtml }}, bypassing JSX protection and requiring prior sanitisation with tools like DOMPurify.
Vue.js (Mustache Interpolation vs v-html)
Vue automatically encodes data bindings using mustache syntax ({{ userInput }}) and v-text. The v-html directive injects unescaped raw HTML nodes, exposing applications to XSS if untrusted input is passed.
Angular (Template Binding and DomSanitizer)
Angular escapes interpolated template values ({{ userInput }}) by default. When binding to [innerHTML], Angular runs input through an internal sanitiser, stripping unsafe script tags unless explicitly trusted via DomSanitizer.
To extract clean text content or tabular structures without executing raw markup, utilities like the HTML Text Extractor and HTML Table Extractor parse data safely into structured text grids.
Privacy & Security: Why Vulnerability Scans and Code Snippets Must Stay Local
Security engineers and developers process sensitive HTML entity strings containing authentication tokens, proprietary source code, and XSS payload logs. Transmitting code snippets to cloud converter sites creates severe privacy risks:
- Source Code Leakage: Uploading HTML templates to third-party sites exposes endpoint paths and secrets in external server logs.
- Vulnerability Disclosure: Inspecting XSS attack payloads on cloud servers alerts third parties to unpatched flaws before fixes are deployed.
- Regulatory Compliance: Sending PII embedded in HTML strings to external servers violates GDPR, HIPAA, and CCPA standards.
EasyExtract eliminates privacy risks through 100% in-browser processing. Built on browser JavaScript Web APIs, entity strings are parsed entirely within local sandbox memory without network transmission.
Frequently Asked Questions
What is the difference between HTML encoding and HTML escaping?
HTML encoding refers to converting characters into named, decimal, or hexadecimal entity references (such as converting © into ©). HTML escaping specifically converts the five core reserved characters (<, >, &, ", and ') into entities to prevent markup parsing errors and XSS vulnerabilities.
Why does an ampersand (&) cause HTML validation errors?
In HTML syntax, the ampersand (&) signals the start of a character reference. When an unescaped ampersand appears in text or URLs (such as page.html?a=1&b=2), the tokenizer expects an entity name. If unaligned, W3C validators flag an invalid reference error. Ampersands must be escaped as & in HTML source code.
Should I use named entities (&) or numeric decimal references (&)?
Named entities (like & or <) are preferable for common reserved characters and typography symbols because they are human-readable. Numeric decimal (&) or hexadecimal (&) references are better for security sanitisation filters because they cover the full Unicode standard without dictionary lookups.
How do I decode HTML entities in JavaScript safely without innerHTML?
Assigning entity strings to element.innerHTML risks XSS if unescaped scripts are present. To decode safely in JavaScript, use the DOMParser Web API: const doc = new DOMParser().parseFromString(encodedString, 'text/html'); const decoded = doc.body.textContent;. This decodes entities into plain text without executing scripts.
Does HTML entity encoding protect against SQL injection attacks?
No. HTML entity encoding only protects against markup parsing errors and XSS in web browsers. SQL injection occurs when untrusted input alters database query logic. Protecting against SQL injection requires database parameterized queries (prepared statements) or ORM abstractions. Entity encoding should only be applied when rendering data in HTML contexts.
Why are trailing semicolons required for HTML5 entities?
Legacy HTML4 parsers permitted certain entity names without trailing semicolons (for example, ©). Non-terminated entities created parsing ambiguity when concatenated with adjacent text (e.g. ∉ vs ¬ing). WHATWG HTML5 standard strictly requires trailing semicolons for all character references to guarantee deterministic tokenization.
Can I extract plain text or tables from entity-encoded HTML files without server uploads?
Yes. EasyExtract provides 100% private, client-side tools for local web file processing. Decode entity strings using the HTML Entity Extractor, strip markup tags to extract plain text with the HTML Text Extractor, or parse HTML table structures into CSV files with the HTML Table Extractor completely inside your browser.
Sources & Standards
This technical guide adheres to official web standards and web security specifications. Consult the authoritative references below for detailed specifications:
- W3C HTML5 Specification (Section 8.5 – Named Character References): World Wide Web Consortium recommendation defining standard character entities and numeric code point mapping rules. W3C Recommendation
- WHATWG HTML Living Standard (Section 13.2.5.72 – Named Character Reference State): The definitive specification governing browser tokenization state transitions and character reference parsing. WHATWG Standard
- OWASP Foundation (Cross-Site Scripting Prevention Cheat Sheet): Operational security guidance detailing context-aware output encoding rules for HTML body, attribute, JavaScript, and CSS execution contexts. OWASP Cheat Sheet
- IETF RFC 3629 (UTF-8, a Transformation Format of ISO 10646): Internet Engineering Task Force standard defining UTF-8 character encoding byte sequences and Unicode scalar representation. IETF RFC 3629