Technical Principles of HTML Entities & XSS Mitigation
HTML (HyperText Markup Language) defines document structures using angle brackets (< >), ampersands (&), and quotation marks (" ') as reserved syntax delimiters for tags and attributes.
If raw user inputs containing <script> or & are rendered directly in HTML, the browser parser misinterprets them as markup tags or entity prefixes. This can break layout structures or allow malicious scripts to execute (Cross-Site Scripting / XSS).
HTML character entity references provide a standardized W3C mechanism (&name; or &#code;) to render reserved characters and Unicode symbols safely without parser interference.
Full Support for Named, Decimal & Hex Formats
Toggle between human-readable Named entities (&), W3C Decimal (&), and Hexadecimal (&) formats.
5 Core Characters vs Non-ASCII Scopes
Choose between standard XSS defense mode (5 core characters) and full non-ASCII Unicode symbol encoding.
Interactive Common Entities Reference Table
Browse currency symbols, math operators, and copyright marks with one-click insertion at your cursor.
Safe DOM-Based Unescape Engine
Leverages browser native DOMParser algorithms to accurately restore all complex entity codes to raw text.
1. The 5 Core Reserved HTML Characters That Must Be Escaped
& & / &):& signals the start of an entity. Writing Tom & Jerry can cause parsing errors if the parser attempts to resolve &Jerry;. It must be written as &.< < / <):<div, <script>). Failing to escape < allows arbitrary tag injection and script execution.> > / >):> to prevent premature tag closing and attribute breakouts." " / "):<input value="user_input">). Unescaped quotes allow attackers to inject malicious event handlers like onload= or onerror=.' ' or '):' is recommended for broad legacy browser compatibility.2. HTML Entity Formats Specification Comparison Table
Reference table comparing Named, Decimal, and Hex representations for common symbols.
| Character | Description & Role | Named Entity | Decimal | Hexadecimal |
|---|---|---|---|---|
| & | Ampersand | & | & | & |
| < | Less Than | < | < | < |
| > | Greater Than | > | > | > |
| " | Double Quote | " | " | " |
| ' | Single Quote | ' (or ') | ' | ' |
| © | Copyright Symbol | © | © | © |
| ® | Registered Trademark | ® | ® | ® |
| ™ | Trademark Symbol | ™ | ™ | ™ |
| € | Euro Currency Symbol | € | € | € |
| Non-breaking space | |   |   |
3. Web Security: XSS Mitigation Principles & Browser DOM Rendering
element.textContent = str, the string is treated strictly as plain text, preventing script execution.element.innerHTML = str, the HTML parser executes markup. If the input contains <img src=x onerror=alert(1)>, malicious JavaScript executes immediately.<input value="${userInput}">, entering " escapes the attribute context to inject event handlers unless quotes are converted to ".4. Implementation Patterns Across Programming Languages
html.escape() and html.unescape().StringEscapeUtils.escapeHtml4() or custom replacement.htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, "UTF-8").System.Net.WebUtility.HtmlEncode() and HtmlDecode().Developer Implementation Snippets for HTML Entity Encoding & Decoding
Production-ready code snippets across JavaScript, Python, PHP, Java, C#, and Go.
| 1 | // 1. Escape 5 core reserved characters (XSS Prevention) |
| 2 | function escapeHTML(str: string): string { |
| 3 | const entityMap: Record<string, string> = { |
| 4 | '&': '&', |
| 5 | '<': '<', |
| 6 | '>': '>', |
| 7 | '"': '"', |
| 8 | "'": ''', |
| 9 | }; |
| 10 | return str.replace(/[&<>"']/g, (s) => entityMap[s]); |
| 11 | } |
| 12 | |
| 13 | // 2. Decode HTML entities via DOMParser |
| 14 | function unescapeHTML(html: string): string { |
| 15 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 16 | return doc.documentElement.textContent || ''; |
| 17 | } |
| 18 | |
| 19 | const raw = '<script>alert("XSS & Hello!");</script>'; |
| 20 | const encoded = escapeHTML(raw); |
| 21 | console.log("Encoded:", encoded); |
| 22 | // Output: <script>alert("XSS & Hello!");</script> |
| 23 | |
| 24 | const decoded = unescapeHTML(encoded); |
| 25 | console.log("Decoded:", decoded); |
| 1 | import html |
| 2 | |
| 3 | # 1. HTML Entity Encoding |
| 4 | raw_text = '<div class="banner">Hello & Welcome!</div>' |
| 5 | encoded = html.escape(raw_text, quote=True) |
| 6 | print("Encoded:", encoded) |
| 7 | # Output: <div class="banner">Hello & Welcome!</div> |
| 8 | |
| 9 | # 2. HTML Entity Decoding |
| 10 | decoded = html.unescape(encoded) |
| 11 | print("Decoded:", decoded) |
| 1 | <?php |
| 2 | $raw = '<a href="test.php?id=1&name=Tom">Click & "Go"</a>'; |
| 3 | |
| 4 | // 1. htmlspecialchars (escapes double and single quotes) |
| 5 | $encoded = htmlspecialchars($raw, ENT_QUOTES | ENT_HTML5, 'UTF-8'); |
| 6 | echo "Encoded: " . $encoded . "\n"; |
| 7 | |
| 8 | // 2. htmlspecialchars_decode (decoding) |
| 9 | $decoded = htmlspecialchars_decode($encoded, ENT_QUOTES | ENT_HTML5); |
| 10 | echo "Decoded: " . $decoded . "\n"; |
| 11 | ?> |
| 1 | public class HtmlEscapeUtil { |
| 2 | // 5-character core HTML escape |
| 3 | public static String escapeHtml(String input) { |
| 4 | if (input == null) return ""; |
| 5 | return input.replace("&", "&") |
| 6 | .replace("<", "<") |
| 7 | .replace(">", ">") |
| 8 | .replace(""", """) |
| 9 | .replace("'", "'"); |
| 10 | } |
| 11 | |
| 12 | public static void main(String[] args) { |
| 13 | String text = "<script>alert('Hello & "World"');</script>"; |
| 14 | String escaped = escapeHtml(text); |
| 15 | System.out.println("Escaped: " + escaped); |
| 16 | } |
| 17 | } |
| 1 | using System; |
| 2 | using System.Net; |
| 3 | |
| 4 | class Program { |
| 5 | static void Main() { |
| 6 | string raw = "<div class="user">Admin & User 'A'</div>"; |
| 7 | |
| 8 | // 1. WebUtility.HtmlEncode |
| 9 | string encoded = WebUtility.HtmlEncode(raw); |
| 10 | Console.WriteLine($"Encoded: {encoded}"); |
| 11 | |
| 12 | // 2. WebUtility.HtmlDecode |
| 13 | string decoded = WebUtility.HtmlDecode(encoded); |
| 14 | Console.WriteLine($"Decoded: {decoded}"); |
| 15 | } |
| 16 | } |
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "html" |
| 6 | ) |
| 7 | |
| 8 | func main() { |
| 9 | raw := "<script>alert('Hello & "World"');</script>" |
| 10 | |
| 11 | // 1. EscapeString |
| 12 | encoded := html.EscapeString(raw) |
| 13 | fmt.Println("Encoded:", encoded) |
| 14 | |
| 15 | // 2. UnescapeString |
| 16 | decoded := html.UnescapeString(encoded) |
| 17 | fmt.Println("Decoded:", decoded) |
| 18 | } |
Client-Side Local Processing FAQ
Q.How does HTML Entity encoding differ from URL Percent-Encoding?
HTML entity encoding replaces reserved markup characters with &, <, > to prevent tag collisions and XSS vulnerabilities in web documents. URL percent-encoding translates characters into %20, %26, %3F to safely transmit parameters across HTTP network requests.
Q.Why is ' preferred over ' for single quotes?
' was introduced in XML and HTML5, but legacy Internet Explorer (IE8 and earlier) did not support it. Decimal ' and hex ' are universally recognized across all legacy and modern browsers.
Q.Do all Unicode and non-English characters need entity encoding?
No. Modern web applications declare <meta charset="UTF-8">, rendering Unicode characters natively without issues. However, entity encoding is useful for legacy email clients or ASCII-only environments.
Q.Do modern frameworks like React and Vue require manual entity encoding?
Standard JSX bindings (<div>{userInput}</div>) and Vue templates (<div>{{ userInput }}</div>) automatically escape text nodes. Manual encoding is only necessary when injecting raw HTML via dangerouslySetInnerHTML or v-html.
Q.What is Double Escaping and how can it be avoided?
Double escaping occurs when an already-escaped string (<div>) is escaped a second time, converting the ampersand into &lt;div&gt;. Ensure sanitization occurs exactly once before DOM rendering.
Q.Is decoding HTML entities safe from executing malicious scripts?
Yes. This tool's decoding engine parses text using virtual text nodes (DOM Text Content), so no JavaScript executes during decoding.
Q.Is my HTML input sent to any remote server?
No. All encoding and decoding run locally in your browser memory via client-side JavaScript.
Q.What is the difference between Decimal and Hexadecimal entities?
Both reference Unicode code points. Decimal uses &# followed by base-10 numbers (<), while Hex uses &#x followed by base-16 hex values (<). Both render identically in web browsers.