Cross-site scripting (XSS) happens when text from a user ends up in a page as markup. A comment like <img src=x onerror=alert(1)> becomes a running script in every visitor's browser. Escaping HTML turns those characters into entities so the browser shows them as text instead of parsing them.
The five characters
| Character | Entity | Why |
|---|---|---|
& |
& |
Starts an entity; must be escaped first |
< |
< |
Starts a tag |
> |
> |
Ends a tag |
" |
" |
Ends a double-quoted attribute |
' |
' |
Ends a single-quoted attribute |
A correct escape function
function escapeHtml(text) {
return String(text)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
escapeHtml('<img src=x onerror="alert(1)">');
// '<img src=x onerror="alert(1)">'
The order matters: replacing & last would turn < into &lt;. A single pass with a lookup table avoids the problem entirely:
const entities = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (ch) => entities[ch]);
Better: don't build HTML strings
In the DOM, the safest escaping is the one you don't have to write. Set text with textContent, and the browser never parses it as markup:
// Unsafe
comment.innerHTML = `<p>${userText}</p>`;
// Safe
const p = document.createElement("p");
p.textContent = userText;
comment.append(p);
Attributes set through the DOM are safe in the same way: link.setAttribute("title", userText).
Frameworks do this for you. React, Vue, Svelte and Angular escape interpolated text, so <p>{userText}</p> in JSX is safe. The escape hatches (dangerouslySetInnerHTML, v-html, {@html}, [innerHTML]) are where XSS comes back.
Context matters
HTML escaping protects text between tags and inside quoted attributes. Other contexts need different handling:
Unquoted attributes
<div title=${escapeHtml(value)}> is still unsafe: a space ends the attribute and starts a new one (x onmouseover=alert(1)). Always quote attribute values.
URLs in href and src
Escaping doesn't stop javascript:alert(1), which contains no special characters at all. Validate the scheme:
function safeUrl(input) {
try {
const url = new URL(input, location.href);
return ["http:", "https:", "mailto:"].includes(url.protocol) ? url.href : "#";
} catch {
return "#";
}
}
Values inside a URL, like query parameters, need percent-encoding first, then HTML escaping if the URL is written into HTML.
Inline scripts
HTML escaping is wrong inside <script>: the browser doesn't decode entities there, and a </script> in a string ends the block. To pass data to scripts, embed JSON with < escaped, or put it in a data- attribute:
const json = JSON.stringify(data).replace(/</g, "\\u003c");
html += `<script type="application/json" id="state">${json}</script>`;
Event handler attributes and styles
onclick="..." and style="..." contain JavaScript and CSS, which have their own syntax. Don't put user data there at all.
When users may submit HTML
Rich text editors, Markdown renderers and email previews need to allow some markup. Escaping everything breaks them; that's the job of a sanitizer, which parses the HTML and removes dangerous elements and attributes:
import DOMPurify from "dompurify";
container.innerHTML = DOMPurify.sanitize(userHtml);
Don't write a regex-based sanitizer. HTML parsing has too many edge cases (malformed tags, encoded characters, SVG and MathML namespaces) for a pattern to cover.
Decoding entities
To turn entities back into text in the browser, let the parser do it without running anything:
function decodeHtml(html) {
const textarea = document.createElement("textarea");
textarea.innerHTML = html;
return textarea.value;
}
decodeHtml("Tom & Jerry <3"); // 'Tom & Jerry <3'
A <textarea>'s content is parsed as text, so tags inside it don't execute. Never decode untrusted entities and then insert the result with innerHTML.
Defense in depth
Escaping is the primary defense, but mistakes happen. A Content Security Policy that disallows inline scripts limits the damage of a missed spot, and HttpOnly cookies keep session tokens out of reach of injected scripts.
Checklist
- Render user text with
textContentor framework interpolation. - When you must build HTML strings, escape
& < > " ', and quote every attribute. - Validate URL schemes for
hrefandsrc. - Embed data for scripts as JSON with
<escaped. - Sanitize, don't escape, when users may submit HTML.
- Add a Content Security Policy as a safety net.
Converting markup for React has its own rules; see HTML vs JSX.