Free HTML Entity Encoder & Decoder (XSS Sanitizer & Character Reference)

Application Security & Frontend Architecture

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.

Input Markup / String 0 chars | 0 lines
Entity Processed Output 0 chars | 0 lines
Copied to clipboard!

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 &amp; &#38; &#x26; Entity starter; must be encoded first to prevent entity injection
< Less-Than &lt; &#60; &#x3C; HTML tag opening delimiter; prevents script injection
> Greater-Than &gt; &#62; &#x3E; HTML tag closing delimiter; prevents premature tag closure
" Double Quotation &quot; &#34; &#x22; HTML attribute value delimiter; prevents attribute escape
' Single Quote (Apostrophe) &apos; &#39; &#x27; 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, '&lt;') 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 (&lt;, &gt;, &amp;) Effective here; stops parser from creating new DOM nodes
HTML Attribute <input type="text" value="USER_INPUT"> Strict Attribute Encoding (&quot;, &#39;) 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! &quot; 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 '%', '>')
WHERE comment_body ILIKE '%
    

The Ambiguous Ampersand & Legacy Semicolon-Less Entity Traps

A subtle historical anomaly in HTML parsing grammar is the Semicolon-Less Named Entity. In early HTML specifications, browsers permitted certain named entities without a terminating semicolon (such as &copy instead of &copy;). This introduces critical URL parsing bugs in modern web applications:

The Semicolon-Less Entity URL Mutation Bug


Click




Click

Mutation XSS (mXSS): When Sanitizers Fail Across Foreign Content

Mutation Cross-Site Scripting (mXSS) represents one of the most sophisticated attack vectors in modern frontend engineering. It occurs when a client-side sanitizer parses an HTML payload as safe, but the browser DOM parser re-serializes or mutates the HTML elements during innerHTML insertion (especially when traversing SVG or MathML namespaces):

  • Namespace Switching Attacks: An attacker wraps malicious payloads inside <svg><style> or <math><annotation-xml> elements. Inside foreign XML namespaces, standard HTML parsing rules are suspended, causing browsers to treat characters like < and > as literal text during initial pass, only to execute them as active executable JavaScript when injected into the live DOM tree.
  • Architectural Mitigation: Never rely on basic string regex replace operations for HTML sanitization. Always utilize battle-tested, actively maintained sanitization engines like DOMPurify with USE_PROFILES: { html: true } to strip dangerous namespace switches.

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 &lt;, > as &gt;) 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' input.txt > output.html
MH

Engineered by Mamun Hossain

Enterprise Systems Architect & Web Security Consultant. Specializing in frontend DOM security architecture, Content Security Policy (CSP Level 3) implementation, and enterprise XSS sanitization audit pipelines.

Frequently Asked Questions About HTML Entity Encoding (PAA)

What is the difference between named, decimal, and hex HTML entities?
Named entities use human-friendly acronyms (such as &copy; for © or &amp; for &). Decimal numeric entities reference the character's Unicode code point in base-10 (e.g., &#169;). Hexadecimal numeric entities reference the Unicode code point in base-16 prefixed with an x (e.g., &#xA9;). All three render identically across modern web browsers.
Does HTML entity encoding prevent all XSS vulnerabilities?
No. HTML entity encoding is strictly designed for HTML body and attribute contexts. It does not protect against XSS if injected into inline JavaScript execution blocks (<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.
Why does & have to be encoded before other characters?
The ampersand is the introductory signal that initiates an HTML entity reference. If you encode < to &lt; first and then encode & to &amp; afterwards, the string mutates into &amp;lt; (double entity encoding), displaying the literal text "&lt;" to users instead of rendering correctly.
Is my text stored or tracked when using this encoder?
No. All entity encoding and decoding algorithms run entirely in memory inside your browser sandbox via JavaScript DOM parsing. Zero keystrokes, HTML snippets, or proprietary content are ever sent to any external server.
& cloud security" — Price: €150/hr

\n
`; encodeHtmlEntities(); } function clearHtml() { document.getElementById('html-input').value = ''; document.getElementById('html-output').value = ''; updateHtmlCounters(); } function copyHtmlOutput() { const text = document.getElementById('html-output').value; if (!text) return; navigator.clipboard.writeText(text).then(() => { showToast('Copied to clipboard!'); }); } function downloadHtmlFile() { const text = document.getElementById('html-output').value || document.getElementById('html-input').value; if (!text) return; const blob = new Blob([text], { type: 'text/html;charset=utf-8' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `html-entities-${Date.now()}.txt`; a.click(); } function showToast(msg) { const t = document.getElementById('zb-toast'); t.innerText = msg; t.style.display = 'block'; setTimeout(() => { t.style.display = 'none'; }, 2500); } document.addEventListener('DOMContentLoaded', () => { loadSampleHtml(); });