HTML Entity Encoder & Decoder
Encode reserved characters to safe HTML entities to prevent XSS attacks, or decode entities back into raw characters.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is HTML Entity Encoding?
HTML Entity Encoding is the fundamental web security and parser mechanism that converts reserved markup syntax characters and non-ASCII glyphs into standard character entity references or Numeric Character References (NCRs). When a web browser renders a document, its HTML parser scans raw byte streams to construct the Document Object Model (DOM). Certain characters—specifically < (less than), > (greater than), & (ampersand), " (double quotation mark), and ' (apostrophe)—serve as control tokens defining tag boundaries, attribute quotes, and entity declarations.
If untrusted user input contains these unescaped control characters and is interpolated directly into an HTML document, the browser's lexer cannot distinguish between application developer markup and attacker-controlled strings. This lexical ambiguity causes Cross-Site Scripting (XSS) vulnerabilities, allowing arbitrary JavaScript execution, session token theft, and interface defacement.
The Affi-Chain HTML Entity Encoder & Decoder provides deterministic, 100% client-side bidirectional conversion between raw string literals, named HTML5 entity strings, decimal numeric character references (&#NN;), and hexadecimal numeric references (&#xHH;), running locally with zero latency.
The Core Reserved Characters & Entity Taxonomy
The W3C HTML5 specification defines over 2,200 named character references, but five foundational entities dictate HTML syntactic validity and baseline injection prevention:
| Character | Description | Named Entity | Decimal NCR | Hexadecimal NCR | Primary Context / Risk |
|---|---|---|---|---|---|
& | Ampersand | & | & | & | Entity delimiter; unescaped ampersands break parsing |
< | Less Than | < | < | < | Opens HTML tags; primary vector for element injection (<script>) |
> | Greater Than | > | > | > | Closes HTML tags; terminates element boundaries |
" | Double Quote | " | " | " | Delimits HTML attribute values (href="...", title="...") |
' | Apostrophe | ' / ' | ' | ' | Delimits single-quoted attributes; ' introduced in XHTML/HTML5 |
Beyond these five reserved tokens, entity references span:
- Typography & Layout:
( , non-breaking space),©(©, copyright),™(™, trademark),—(—, em dash). - Mathematical & Logical Symbols:
±(±, plus-minus),√(√, square root),∞(∞, infinity),≠(≠, not equal). - Currency Glyphs:
€(€, Euro),£(£, British Pound),¥(¥, Japanese Yen). - Greek & Multilingual Alphabets:
α(α),β(β),Ω(Ω).
Named Entities vs Numeric Character References (Decimal vs Hex)
Developers encounter three distinct formats when encoding HTML entities. Understanding their parser behavior ensures cross-platform compatibility across HTML, XML, SVG, and legacy user agents:
1. Named Character References (&name;)
Named entities use human-readable mnemonic abbreviations (e.g., © for © or → for →). While convenient and readable, older XML parsers (including strict RSS feeds and XHTML engines) reject named entities other than the core five unless an external Document Type Definition (DTD) is explicitly declared.
2. Decimal Numeric Character References (&#[0-9]+;)
Decimal NCRs represent the character's exact Unicode code point in base-10. For instance, the double quotation mark (") has a decimal Unicode code point of 34, yielding ". Decimal NCRs are supported identically across all HTML, XML, and SVG rendering engines without requiring DTD schemas.
3. Hexadecimal Numeric Character References (&#x[0-9A-Fa-f]+;)
Hex NCRs express the Unicode scalar value in base-16 notation, prefixed with an x (e.g., " for " or < for <). Hexadecimal NCRs match standard Unicode representations (U+003C) directly, making them the industry standard for strict XML serialization and automated code generation.
Practical Implementation Examples Across Languages
1. Modern JavaScript (Node.js & Modern Browser Runtimes)
In client-side JavaScript, assigning untrusted text via .innerText or .textContent automatically escapes content at the DOM layer. However, when constructing server-rendered templates or raw markup streams, explicit string-level replacement is required:
/**
* Sanitizes a string by escaping the 5 critical HTML control characters.
* @param {string} rawString - The unescaped input string.
* @returns {string} Safe HTML string.
*/
function escapeHtml(rawString) {
if (typeof rawString !== 'string') return '';
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return rawString.replace(/[&<>"']/g, (char) => entityMap[char]);
}
/**
* Decodes HTML entities back to raw character strings.
* @param {string} htmlString - String containing encoded entities.
* @returns {string} Unescaped plain text.
*/
function decodeHtmlEntities(htmlString) {
if (typeof htmlString !== 'string') return '';
// In browser environments:
if (typeof window !== 'undefined' && window.DOMParser) {
const doc = new DOMParser().parseFromString(htmlString, 'text/html');
return doc.documentElement.textContent || '';
}
// Server-side regex fallback for standard entities:
const reverseMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
''': "'"
};
return htmlString.replace(/&(?:amp|lt|gt|quot|#39|apos);/g, (entity) => reverseMap[entity]);
}
// Verification:
const payload = '<script>alert("XSS Attack & Theft");</script>';
const safeMarkup = escapeHtml(payload);
console.log(safeMarkup);
// Output: <script>alert("XSS Attack & Theft");</script>
2. Python 3 (Standard Library html Module)
Python provides built-in enterprise-grade entity handling within its standard distribution:
import html
# Unescaped user-generated content
user_comment = '5 > 3 & 2 < 4: "Winner\'s bracket"'
# Encoding with single-quote escaping enabled (quote=True)
safe_html = html.escape(user_comment, quote=True)
print(f"Escaped: {safe_html}")
# Escaped: 5 > 3 & 2 < 4: "Winner's bracket"
# Full round-trip decoding
raw_restored = html.unescape(safe_html)
assert raw_restored == user_comment
print("Round-trip validation: 100% matched.")
3. PHP Enterprise Web Applications
PHP provides htmlspecialchars() with granular flag parameters:
<?php
$user_input = '<a href="/test?a=1&b=2">Click & Win</a>';
// ENT_QUOTES encodes both double and single quotes
// ENT_SUBSTITUTE replaces invalid code unit sequences
// ENT_HTML5 treats code as HTML5 specification
$safe_output = htmlspecialchars($user_input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
echo $safe_output;
// <a href="/test?a=1&b=2">Click & Win</a>
?>
Comparison Matrix: HTML Encoding vs Alternative Encoding Schemes
Engineers must choose the correct encoding mechanism based on where data is inserted within the web stack:
| Encoding Mechanism | Target Boundary | Primary Control Tokens Escaped | Example Output (<foo> & "bar") | Security Risk If Misapplied |
|---|---|---|---|---|
| HTML Entity Encoding | HTML Body & Quoted Attributes | <, >, &, ", ' | <foo> & "bar" | Ineffective inside <script> blocks or inline CSS style sheets |
| URL Percent-Encoding | Query Parameters & URI Paths | Space (%20), ?, &, =, # | %3Cfoo%3E%20%26%20%22bar%22 | Browsers do not decode URLs inside HTML element text nodes |
| JSON Escaping | Serialized API Payloads | Quotes (\"), Newlines (\n), \\ | "<foo> & \\"bar\\"" | Raw JSON inserted into <script> tags remains vulnerable to </script> breakouts |
| Base64 Encoding | Binary Data in Text Transport | Binary octets to 64 ASCII chars | PGZvbz4gJiAiYmFyIg== | High payload bloat (+33%); unreadable without client decoding step |
Critical Edge Cases & Security Pitfalls
1. The Context-Specific Injection Vulnerability
A universal security mistake is assuming HTML entity encoding protects every web context. HTML entity encoding is ONLY valid for text nodes (<div>...</div>) and attribute values (<input value="...">).
- Inside
<script>Tags: If an application places entity-encoded strings inside a JavaScript block, the JavaScript engine parses entity characters literally or encounters syntax errors:<!-- DANGEROUS! HTML entity encoding does NOT prevent JavaScript breakout --> <script> let username = '"; maliciousPayload();//'; </script> - Inside
hrefAttribute URLs: If untrusted input starts withjavascript:, HTML entity encoding does not stop execution:
Solution: Validate URI protocols (allow only<!-- DANGEROUS! Browsers unescape HTML entities BEFORE evaluating URIs --> <a href="javascript:alert(1)">Click</a>http://orhttps://) before rendering links.
2. Double Encoding Traps
Double encoding occurs when an already-encoded string is passed through an encoder a second time.
- Input:
AT&T - First Pass:
AT&T - Second Pass:
AT&amp;T - Browser Renders:
AT&T(broken text visibly shown to users).
Always enforce a single sanitization step immediately prior to document rendering, or use idempotent sanitization routines.
3. XML / SVG Parser Discrepancies
Standard HTML5 parsers tolerate named entities without trailing semicolons in legacy quirks modes (e.g., © without ;). However, modern SVG images, XHTML documents, and XML feeds will immediately abort with fatal XML Parsing Error: undefined entity if unclosed or non-standard named entities appear. Always ensure full semicolon termination (©) and prefer numeric references (© or ©) when authoring SVG or XML feeds.