HTML Entity Encoder & Decoder

Encode reserved characters to safe HTML entities to prevent XSS attacks, or decode entities back into raw characters.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:UUID / GUID Generator (v4 & v1) →Cron Expression Generator & Schedule Builder →Lorem Ipsum Placeholder Text Generator →Markdown to HTML Editor & Previewer →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

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:

CharacterDescriptionNamed EntityDecimal NCRHexadecimal NCRPrimary Context / Risk
&Ampersand&amp;&#38;&#x26;Entity delimiter; unescaped ampersands break parsing
<Less Than&lt;&#60;&#x3C;Opens HTML tags; primary vector for element injection (<script>)
>Greater Than&gt;&#62;&#x3E;Closes HTML tags; terminates element boundaries
"Double Quote&quot;&#34;&#x22;Delimits HTML attribute values (href="...", title="...")
'Apostrophe&#39; / &apos;&#39;&#x27;Delimits single-quoted attributes; &apos; introduced in XHTML/HTML5

Beyond these five reserved tokens, entity references span:

  1. Typography & Layout: &nbsp; (&#160;, non-breaking space), &copy; (&#169;, copyright), &trade; (&#8482;, trademark), &mdash; (&#8212;, em dash).
  2. Mathematical & Logical Symbols: &plusmn; (&#177;, plus-minus), &radic; (&#8730;, square root), &infin; (&#8734;, infinity), &ne; (&#8800;, not equal).
  3. Currency Glyphs: &euro; (&#8364;, Euro), &pound; (&#163;, British Pound), &yen; (&#165;, Japanese Yen).
  4. Greek & Multilingual Alphabets: &alpha; (&#945;), &beta; (&#946;), &Omega; (&#937;).

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., &copy; for © or &rarr; 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 &#34;. 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., &#x22; for " or &#x3C; 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 = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };
  
  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 = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#39;': "'",
    '&apos;': "'"
  };
  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: &lt;script&gt;alert(&quot;XSS Attack &amp; Theft&quot;);&lt;/script&gt;

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 &gt; 3 &amp; 2 &lt; 4: &quot;Winner&#x27;s bracket&quot;

# 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;
// &lt;a href=&quot;/test?a=1&amp;b=2&quot;&gt;Click &amp; Win&lt;/a&gt;
?>

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 MechanismTarget BoundaryPrimary Control Tokens EscapedExample Output (<foo> & "bar")Security Risk If Misapplied
HTML Entity EncodingHTML Body & Quoted Attributes<, >, &, ", '&lt;foo&gt; &amp; &quot;bar&quot;Ineffective inside <script> blocks or inline CSS style sheets
URL Percent-EncodingQuery Parameters & URI PathsSpace (%20), ?, &, =, #%3Cfoo%3E%20%26%20%22bar%22Browsers do not decode URLs inside HTML element text nodes
JSON EscapingSerialized API PayloadsQuotes (\"), Newlines (\n), \\"<foo> & \\"bar\\""Raw JSON inserted into <script> tags remains vulnerable to </script> breakouts
Base64 EncodingBinary Data in Text TransportBinary octets to 64 ASCII charsPGZvbz4gJiAiYmFyIg==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 = '&quot;; maliciousPayload();//';
    </script>
    
  • Inside href Attribute URLs: If untrusted input starts with javascript:, HTML entity encoding does not stop execution:
    <!-- DANGEROUS! Browsers unescape HTML entities BEFORE evaluating URIs -->
    <a href="&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;alert(1)">Click</a>
    
    Solution: Validate URI protocols (allow only http:// or https://) 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&amp;T
  • Second Pass: AT&amp;amp;T
  • Browser Renders: AT&amp;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., &copy 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 (&copy;) and prefer numeric references (&#169; or &#xA9;) when authoring SVG or XML feeds.

Frequently Asked Questions

Why must HTML entities be encoded?
Encoding reserved characters ensures that user-submitted content displays safely as plain text without being executed as active HTML code.

Explore Related Utilities