HTML Entity Encoder & Decoder
Convert raw HTML markup and reserved characters into named, decimal, and hexadecimal HTML entities to mitigate Cross-Site Scripting (XSS) or decode encoded entities back to plaintext. 100% Client-Side Execution.
The Architecture of HTML Character References: RFC & W3C Standards
HTML documents are parsed as hierarchical SGML/XML-derived token trees. To distinguish between active structural markup tags (such as <div>, <script>, or <a href="...">) and human-readable text content, the W3C and WHATWG HTML5 specifications designate five primary Reserved Characters: the ampersand (&), the less-than symbol (<), the greater-than symbol (>), the double quote ("), and the single quote/apostrophe (').
When these characters appear in raw user-generated data without proper transformation into HTML Character References (entities), browser DOM parsers switch into tag-construction mode, triggering browser rendering corruption or devastating security vulnerabilities like Cross-Site Scripting (XSS).
| Character | Character Name | Named Entity | Decimal Numeric | Hexadecimal Numeric | Critical Security Context |
|---|---|---|---|---|---|
& |
Ampersand | & |
& |
& |
Entity starter; must be encoded first to prevent entity injection |
< |
Less-Than | < |
< |
< |
HTML tag opening delimiter; prevents script injection |
> |
Greater-Than | > |
> |
> |
HTML tag closing delimiter; prevents premature tag closure |
" |
Double Quotation | " |
" |
" |
HTML attribute value delimiter; prevents attribute escape |
' |
Single Quote (Apostrophe) | ' |
' |
' |
Single-quoted attribute delimiter; prevents attribute escape |
Context-Aware Output Encoding: Preventing Cross-Site Scripting (XSS)
A fatal assumption in web development is believing that running a basic replace(/</g, '<') is sufficient to prevent XSS attacks. According to the OWASP XSS Prevention Cheat Sheet, output encoding must be strictly tailored to the DOM execution context:
| DOM Context | Example Vulnerable Injection Point | Required Encoding Strategy | Why Basic HTML Encoding Fails |
|---|---|---|---|
| HTML Body | <div>USER_INPUT</div> |
Standard HTML Entity Encoding (<, >, &) |
Effective here; stops parser from creating new DOM nodes |
| HTML Attribute | <input type="text" value="USER_INPUT"> |
Strict Attribute Encoding (", ') |
Unquoted attributes can execute payloads like onfocus=alert(1) without quotes |
| JavaScript Context | <script>let id = 'USER_INPUT';</script> |
Unicode Escape Encoding (\u0027, \u0022) |
HTML entities do not execute in JS! " causes syntax error or breaks |
| URI / Href Context | <a href="USER_INPUT">Click Here</a> |
Protocol Allowlisting (https://) + Percent-Encoding |
HTML encoding does not prevent javascript:alert(document.cookie) links! |
The Legacy PHP htmlspecialchars() Trap
In legacy backend development (especially in PHP web applications), developers frequently invoked htmlspecialchars($input) without arguments, assuming full sanitization. However, in PHP versions prior to 8.1, the default flag was ENT_COMPAT:
PHP htmlspecialchars Default Flag Vulnerability
// VULNERABLE IN PHP < 8.1: echo htmlspecialchars($user_input); // ENT_COMPAT: Encodes double quotes, LEAVES SINGLE QUOTES UNTOUCHED! // Attacker Payload in Single-Quoted Attribute: // // Payload: test' onmouseover='alert(1) // Result: (CRITICAL XSS!) // PRODUCTION-HARDENED CALL: echo htmlspecialchars($user_input, ENT_QUOTES | ENT_HTML5, 'UTF-8'); // Encodes both double & single quotes
Content Security Policy (CSP Level 3): Defense-in-Depth Beyond Output Encoding
While contextual HTML entity encoding neutralizes standard DOM-based and Reflected Cross-Site Scripting (XSS), robust modern web architecture requires a multi-layered defense strategy. Relying solely on entity encoding leaves applications vulnerable to developer oversights, legacy third-party jQuery plugins, and template engine bypasses.
The industry standard second line of defense is a production-hardened Content Security Policy (CSP Level 3) enforced via HTTP response headers:
| CSP Directive | Production Recommended Value | Security Defense Role |
|---|---|---|
default-src |
'self' |
Restricts all asset loading to origin by default |
script-src |
'strict-dynamic' 'nonce-{RANDOM}' https: 'unsafe-inline' |
Neutralizes XSS: Browser rejects any script without a cryptographically valid per-request nonce |
object-src |
'none' |
Completely disables dangerous plugins (Flash, Java Applets, ActiveX) |
base-uri |
'self' |
Prevents malicious base-tag injection (<base href="...">) hijacking relative paths |
frame-ancestors |
'none' or 'self' |
Replaces legacy X-Frame-Options to eliminate Clickjacking |
DOMPurify vs HTML Entity Encoding: Architectural Decision Tree
Frontend engineers frequently ask: “When should I entity-encode user input versus sanitizing it with a library like DOMPurify?”
- Use HTML Entity Encoding When: You want to display raw user text exactly as typed (e.g., usernames, comments, code snippets, chat messages). Entity encoding renders
<b>Hello</b>as literal text on screen without formatting. - Use HTML Sanitization (DOMPurify) When: You need to permit safe Rich Text formatting (e.g., bold, italics, tables, and hyperlinks in blog comments or CMS editors) while stripping malicious script vectors (
<script>,<img onerror=...>,<iframe>).
Disaster Recovery Runbook: Remediating Stored XSS in Relational Databases
If an unescaped stored XSS payload penetrates your database tables via an unvalidated administrative API endpoint, execute this emergency database remediation runbook to clean stored data without corrupting legitimate customer text:
PostgreSQL Stored XSS Inspection & Sanitization Script
-- Step 1: Scan for suspected malicious script injections
SELECT id, user_id, comment_body
FROM comments
WHERE comment_body ILIKE '%
Anatomy of Polyglot XSS Vectors & Defense Mechanisms
Advanced security penetration testers frequently utilize Polyglot XSS Payloads—carefully crafted attack strings engineered to break out of multiple nesting contexts simultaneously, whether injected into raw HTML body text, double-quoted attributes, single-quoted JavaScript string variables, or SVG markup:
Canonical XSS Polyglot Attack Vector
javascript:/*-->-->
Notice how this single payload contains premature closing tags (</title>, </style>, </textarea>) to shatter open containers, followed by an inline XML/SVG event handler. The only bulletproof defense against such universal vectors is strict HTML entity encoding of all angle brackets (< as <, > as >) at the server rendering layer, ensuring the browser DOM tree never instantiates untrusted tags.
Subresource Integrity (SRI) Hash Verification
Beyond local output encoding, enterprise web security mandates Subresource Integrity (SRI - W3C Standard) for all third-party JavaScript libraries loaded from CDNs. SRI enables browsers to verify that remote script files have not been maliciously modified or compromised by verifying a cryptographic SHA-384 hash before execution:
Subresource Integrity (SRI) Implementation
<script src="https://cdn.example.com/analytics.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
Terminal Mastery: HTML Entity Encoding via Python, Node & PHP CLI
For automated data pipelines, command-line scripts can sanitize raw database dumps and text files before HTML email dispatch or static site generation:
- Python CLI One-Liner:
python3 -c "import html, sys; print(html.escape(sys.argv[1], quote=True))" '<script>alert(1)</script>' - PHP CLI One-Liner:
php -r "echo htmlspecialchars(\$argv[1], ENT_QUOTES | ENT_HTML5, 'UTF-8') . PHP_EOL;" '<a href="test">' - Linux sed Entity Replacement:
sed 's/&/\&/g; s/\</g; s/>/\>/g; s/\"/\"/g' input.txt > output.html
Frequently Asked Questions About HTML Entity Encoding (PAA)
© for © or & for &). Decimal numeric entities reference the character's Unicode code point in base-10 (e.g., ©). Hexadecimal numeric entities reference the Unicode code point in base-16 prefixed with an x (e.g., ©). All three render identically across modern web browsers.<script>), stylesheet blocks (<style>), or protocol schemes (e.g., javascript: URLs). For complete defense, combine context-specific encoding with strict Content Security Policy (CSP) headers and DOMPurify sanitization.< to < first and then encode & to & afterwards, the string mutates into &lt; (double entity encoding), displaying the literal text "<" to users instead of rendering correctly.