HTML Escape Encoders
Input Text
Encoded Output
What is HTML Entity Encoding?
HTML entity encoding is a method of representing special characters in HTML documents using character references. It converts characters that have special meaning in HTML (like <, >, &, and quotes) into their entity equivalents to ensure they display correctly and prevent security vulnerabilities like Cross-Site Scripting (XSS) attacks.
How Does HTML Entity Encoding Work?
HTML entity encoding replaces special characters with their corresponding HTML entity references. These references can be named entities (like < for <) or numeric entities (like < for <). The browser interprets these entities and displays the intended character without executing any potentially harmful code.
XSS Protection
Prevent Cross-Site Scripting attacks by encoding user input before displaying it.
Display Code
Show HTML code snippets on web pages without browser interpretation.
Unicode Support
Encode international characters and symbols using numeric entities.
Standards Compliant
Ensure your HTML is valid and properly encoded for all browsers.
Common Use Cases for HTML Entity Encoding
- Security: Prevent XSS attacks by encoding user-generated content before displaying it.
- Code Display: Show HTML, XML, or code examples on web pages without execution.
- Special Characters: Display reserved HTML characters like <, >, & in text content.
- Email Templates: Ensure special characters display correctly in HTML emails.
- Form Data: Safely display user input in form fields and text areas.
- RSS/XML Feeds: Properly encode content for syndication formats.
- Documentation: Write technical documentation with code examples.
HTML Entity Examples
Common HTML Entities:
< becomes <> becomes >& becomes &" becomes "' becomes ' or '
XSS Prevention Example:
Input: <script>alert('XSS')</script>Output: <script>alert('XSS')</script>The script tag is displayed as text instead of being executed
Unicode Entity Example:
© becomes © or ©€ becomes € or €™ becomes ™ or ™
Frequently Asked Questions
Why is HTML entity encoding important for security?
HTML entity encoding prevents malicious scripts from being executed when displaying user input. It's a crucial defense against Cross-Site Scripting (XSS) attacks, ensuring that any HTML or JavaScript code is displayed as text rather than executed by the browser.
What's the difference between named and numeric entities?
Named entities use descriptive names (like < for less than), while numeric entities use decimal (<) or hexadecimal (<) character codes. Named entities are more readable but limited in number, while numeric entities can represent any Unicode character.
Should I encode all HTML content?
No, only encode content that could be interpreted as HTML markup or that contains special characters. User-generated content, dynamic data, and code examples should always be encoded. Static HTML structure should not be encoded.
How do I decode HTML entities?
Use our decoder mode to convert HTML entities back to their original characters. In programming, use functions like html_entity_decode() in PHP or DOMParser in JavaScript.
Technical Specifications
| Entity Type | Format | Example |
|---|---|---|
| Named Entity | &name; | < > & |
| Decimal Entity | &#decimal; | < > & |
| Hexadecimal Entity | &#xhex; | < > & |
| Standards | HTML 4.01, HTML5, XML | W3C Specifications |
Developer Guide
// Client-side encoding
function encodeHTML(str) {
return str
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Using the API
async function encodeWithAPI(text) {
const response = await fetch('/tools/html-escape', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
text: text,
mode: 'encode',
options: ['encode-quotes', 'encode-newlines']
})
});
const result = await response.json();
console.log('Encoded:', result.result);
}
<?php
// Basic HTML encoding
$userInput = $_POST['comment'];
$safeOutput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $safeOutput;
// Full entity encoding
function fullHtmlEncode($string) {
$encoded = '';
$length = mb_strlen($string, 'UTF-8');
for ($i = 0; $i < $length; $i++) {
$char = mb_substr($string, $i, 1, 'UTF-8');
$ord = mb_ord($char, 'UTF-8');
$encoded .= '' . $ord . ';';
}
return $encoded;
}
// XSS-safe output
function xssSafe($data) {
return htmlentities($data, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
?>
import html
import requests
# Encode HTML entities
def encode_html(text):
return html.escape(text, quote=True)
# Decode HTML entities
def decode_html(text):
return html.unescape(text)
# Full numeric encoding
def full_encode(text):
return ''.join(f'{ord(char)};' for char in text)
# Using the API
def encode_with_api(text):
response = requests.post('https://yourdomain.com/tools/html-escape',
data={
'text': text,
'mode': 'encode',
'options[]': ['encode-quotes', 'numeric-entities']
}
)
result = response.json()
return result['result']
# Example usage
dangerous_html = '<script>alert("XSS")</script>'
safe_html = encode_html(dangerous_html)
print(f"Safe: {safe_html}")
# Output: <script>alert("XSS")</script>
// 1. Always encode user input before displaying
const userComment = getUserInput();
const safeComment = encodeHTML(userComment);
document.getElementById('comment').innerHTML = safeComment;
// 2. Use Content Security Policy
// Add to your HTML head:
// <meta http-equiv="Content-Security-Policy"
// content="default-src 'self'; script-src 'self'">
// 3. Validate and sanitize on server-side
function validateAndEncode($input) {
// Remove any existing HTML tags
$input = strip_tags($input);
// Encode special characters
$input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// Additional filtering if needed
$input = filter_var($input, FILTER_SANITIZE_STRING);
return $input;
}
// 4. Use prepared statements for database queries
$stmt = $pdo->prepare("INSERT INTO comments (text) VALUES (?)");
$stmt->execute([validateAndEncode($userInput)]);