HTML String Escape
Escape and unescape special characters in HTML strings to prevent XSS attacks
About HTML String Escaping
HTML string escaping is the process of converting HTML special characters into entity references. This is crucial for preventing XSS (Cross-Site Scripting) attacks, safely displaying user input, and ensuring HTML document validity.
When embedding content containing special characters in HTML, these characters must be escaped, otherwise browsers will interpret them as HTML tags or attributes, causing display errors or security vulnerabilities.
Why Escape?
- Prevent XSS (Cross-Site Scripting) attacks
- Safely display user-submitted content
- Embed text containing special characters in HTML
- Ensure HTML document validity
- Safely handle HTML strings in JavaScript
HTML Escape Rules
| Original Character | Named Entity | Numeric Entity | Hexadecimal Entity | Description |
|---|---|---|---|---|
| < | < | < | < | Less than |
| > | > | > | > | Greater than |
| & | & | & | & | Ampersand |
| " | " | " | " | Double quote |
| ' | ' | ' | ' | Apostrophe |
| |   |   | Non-breaking space |
Common Use Cases
User Input Display
Safely display user-submitted comments, messages, and other content on web pages to prevent malicious script injection.
Dynamic Content Generation
Ensure special characters are properly escaped when dynamically generating HTML content in JavaScript.
Template Rendering
Automatically escape special characters when rendering data in template engines to ensure security.
API Data Display
Safely display data retrieved from APIs in HTML pages.
XSS Attack Prevention
XSS (Cross-Site Scripting) attacks are one of the most common web security vulnerabilities. Attackers inject malicious scripts into web pages to steal user information, hijack sessions, etc. Proper HTML escaping is the first line of defense against XSS attacks.
Usage Tips
- Always escape HTML when displaying user input
- Use automatic escaping features provided by frameworks (like Vue's v-text, React's default behavior)
- Only use v-html or dangerouslySetInnerHTML when you actually need to render HTML
- Escape all user-controllable data including URL parameters, form inputs, cookies
- Use Content Security Policy (CSP) as an additional security layer
Entity Types Description
Named Entity:Named entities use memorable names, such as < for less than
Numeric Entity:Numeric entities use decimal Unicode code points, such as < for less than
Hexadecimal Entity:Hexadecimal entities use hexadecimal Unicode code points, such as < for less than