Encodeur/Décodeur HTML
Encodez et décodez les entités HTML pour affichage sécurisé du texte
What Are HTML Entities?
HTML entities are special sequences that represent characters which have reserved meaning in HTML markup
or cannot be typed directly on a keyboard. When a browser encounters <, it renders
the literal less-than sign (<) instead of interpreting it as the start of an HTML tag.
This mechanism is fundamental to web security and correct rendering of user-generated content. Without
entity encoding, any text containing angle brackets, ampersands, or quotation marks can break page layout
or — far worse — open the door to cross-site scripting (XSS) attacks.
This tool converts special characters into their HTML entity equivalents (encoding) and reverses the
process (decoding). It handles both named entities like &, <,
>, ", and ', as well as numeric
entities in decimal (<) and hexadecimal (<) notation.
Use it to sanitize content before inserting it into HTML, or to inspect what encoded text actually
represents when debugging templates and API responses.
XSS Prevention Through HTML Encoding
Cross-site scripting (XSS) remains one of the most prevalent web vulnerabilities year after year, consistently appearing in the OWASP Top 10. The attack exploits the fact that browsers cannot distinguish between legitimate markup authored by the developer and malicious markup injected by an attacker through user input. HTML encoding neutralizes this threat by converting every dangerous character into a harmless entity reference before the browser can interpret it as executable code.
Consider a comment field where a user submits <script>alert('xss')</script>.
Without encoding, the browser executes that script in the context of your page, giving the attacker
access to cookies, session tokens, and the DOM. After encoding, the same input becomes
<script>alert('xss')</script> — rendered as visible text
with no execution. The five critical characters to encode are: < (less-than),
> (greater-than), & (ampersand), " (double quote),
and ' (single quote / apostrophe).
Modern frameworks like React, Angular, and Vue automatically encode output by default, but raw
HTML rendering via dangerouslySetInnerHTML, [innerHTML], or v-html
bypasses this protection. Server-side template engines also vary in their default behavior — always
verify that your rendering pipeline encodes untrusted data at the output boundary.
Named vs Numeric Entities
HTML supports two systems for representing characters as entities. Named entities use human-readable
labels defined in the HTML specification — & for ampersand, ©
for the copyright symbol, — for an em dash. The HTML5 specification defines
over 2,200 named character references covering mathematical symbols, typographic characters, arrows,
and language-specific glyphs.
Numeric entities reference characters by their Unicode code point. Decimal notation uses the format
&#nnnn; (e.g., © for ©), while hexadecimal notation
uses &#xhhhh; (e.g., © for ©). Numeric entities
can represent any Unicode character, including those without named references. This makes them
essential for emoji (😀 for 😀), CJK characters, and rare symbols.
In practice, use named entities for the five security-critical characters (<,
>, &, ", ')
because they are self-documenting and widely supported. Use numeric entities when you need to
represent characters that lack a named reference or when you want to ensure compatibility with
XML parsers that only recognize a subset of HTML named entities.
Encoding vs Escaping: Understanding the Difference
Developers often use "encoding" and "escaping" interchangeably, but they serve different purposes. HTML encoding transforms characters into entity references for safe rendering in an HTML context. Escaping, more broadly, refers to prefixing or wrapping characters so they lose their special meaning in a given language — backslash-escaping in strings, URL percent-encoding, or SQL parameterization.
The distinction matters because each output context requires its own encoding scheme. Content
inserted into an HTML attribute needs HTML entity encoding. Content placed inside a JavaScript
string literal needs JavaScript escaping (or JSON serialization). Content embedded in a URL path
needs percent-encoding. Applying the wrong encoding type creates false security — HTML-encoding
a value that ends up inside a <script> block does not prevent XSS because
the browser first interprets the script content, then decodes entities.
The golden rule is: encode for the innermost context where the data will be interpreted. If you
are inserting a user value into an href attribute, you need URL encoding first,
then HTML attribute encoding on the result. This tool handles the HTML layer — pair it with
URL encoding or JavaScript escaping for multi-context scenarios.
When to Use HTML Encoding and Browser Auto-Decoding
Use HTML encoding whenever you insert untrusted text into an HTML document: user comments,
database-retrieved strings, API responses, form field echoing, and URL parameter display. Also
encode when constructing HTML strings programmatically in JavaScript via innerHTML
or template literals — any context where the browser will parse the string as HTML.
You do not need to encode text set via textContent or innerText in
JavaScript, because these properties treat the assigned value as plain text and never parse HTML.
Similarly, values set through DOM property assignment (e.g., input.value = userText)
are safe without encoding because they bypass the HTML parser entirely.
Browsers automatically decode entities when rendering HTML. This means that
<b>bold</b> displays as the literal text
<b>bold</b> — the user sees the tags as text, not as bold formatting.
This auto-decoding also applies when you read textContent from a DOM node: the
browser returns the decoded characters, not the raw entity references. Understanding this
round-trip behavior is essential when building pipelines that read, transform, and re-render HTML
content — double-encoding (&lt;) is a common bug that causes entity sequences
to appear literally on the page instead of being decoded.
Code Examples
HTML encoding and decoding in JavaScript
// Encode: replace dangerous characters with HTML entities
function htmlEncode(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Decode: leverage the browser's built-in HTML parser
function htmlDecode(encoded) {
const textarea = document.createElement('textarea');
textarea.innerHTML = encoded;
return textarea.value;
}
// Usage — preventing XSS in dynamic content
const userInput = '<img src=x onerror="alert(1)">';
const safe = htmlEncode(userInput);
// → '<img src=x onerror="alert(1)">'
document.getElementById('comment').innerHTML = safe;
// Renders as visible text, not as an image tagOutput:
// Encoded: <img src=x onerror="alert(1)">
// Decoded back: <img src=x onerror="alert(1)">Server-side encoding in Node.js without dependencies
// Named entities map for common characters
const ENTITY_MAP = {
'&': '&', '<': '<', '>': '>',
'"': '"', "'": ''',
'/': '/', '`': '`', '=': '='
};
function escapeHtml(str) {
return String(str).replace(/[&<>"'`=/]/g,
(char) => ENTITY_MAP[char]
);
}
// In Express.js templates (when not using a template engine)
app.get('/profile', (req, res) => {
const name = escapeHtml(req.query.name || 'Guest');
res.send(`<h1>Hello, ${name}</h1>`);
});
// ?name=<script>alert(1)</script>
// → <h1>Hello, <script>alert(1)</script></h1>Standards & Specifications
- HTML Living Standard — Named Character References — Complete list of 2,231 named character references recognized by HTML parsers
- OWASP XSS Prevention Cheat Sheet — Industry-standard rules for output encoding to prevent cross-site scripting attacks
Questions Fréquentes
What is HTML encoding and why is it important?
HTML encoding converts special characters into HTML entities to prevent them from being interpreted as HTML markup. It's crucial for security, preventing XSS (Cross-Site Scripting) attacks by ensuring user input is displayed as text rather than executed as code. For example, '<script>' becomes '<script>', which displays safely without executing.
What's the difference between HTML encoding and URL encoding?
HTML encoding converts characters to HTML entities (like < for <) for safe display in HTML documents. URL encoding converts characters to percent-encoded format (like %3C for <) for safe transmission in URLs. They serve different purposes: HTML encoding is for displaying content, while URL encoding is for transmitting data in URLs.
When should I use HTML encoding?
Use HTML encoding whenever you display user-generated content or dynamic data in HTML. This includes form inputs, comments, usernames, search results, and any content that might contain special characters. It's essential for preventing XSS attacks and ensuring content displays correctly without breaking your HTML structure.
What are named entities vs numeric entities?
Named entities use descriptive names like & for ampersand or © for copyright symbol. Numeric entities use character codes in decimal (&60;) or hexadecimal (&x3C;) format. Named entities are more readable but limited to predefined characters. Numeric entities can represent any Unicode character but are less human-friendly.
Can I encode emoji and Unicode characters?
Yes! This tool handles all Unicode characters correctly, including emoji. You can encode them as numeric entities if needed. However, modern HTML5 supports UTF-8 encoding directly, so emoji usually don't need to be encoded unless you're working with legacy systems or need to ensure compatibility with older browsers.
Does HTML encoding affect SEO or page performance?
HTML encoding has minimal impact on SEO and performance. Search engines correctly interpret HTML entities, and modern browsers decode them efficiently. The encoding process itself is very fast. The security and correctness benefits far outweigh any negligible performance cost.
Is my data sent to a server?
No, all encoding and decoding happens in your browser using JavaScript. Your data never leaves your device, ensuring complete privacy and security. This is especially important when working with sensitive content or user data.