Escaping HTML entities is one of those fundamentals that's easy to overlook until something breaks — or worse, until someone injects a script into your page. If you've ever seen a user's name render as a dialog box popping up, or watched a page explode because somebody typed a < into a form, you've met the consequences of skipping it.
What HTML escaping actually is
Certain characters have special meaning in HTML. The browser treats < as the start of a tag, & as the start of an entity reference, and so on. Escaping means replacing those characters with their entity equivalents so the browser renders them as literal text instead of interpreting them as markup.
The core set you'll deal with most often:
&becomes&<becomes<>becomes>"becomes"'becomes'(or', though'is safer across contexts)
Escape the ampersand first. If you do it last, you'll double-escape everything else — turning < into &lt;, which renders as literal < on the page.
When and why you'd use it
The short version: escape any untrusted data before it lands in HTML. "Untrusted" means anything you didn't hardcode yourself — user input, database values, API responses, URL parameters, filenames. If it could ever contain characters a user controls, it needs escaping.
Preventing XSS
This is the big one. Cross-site scripting happens when attacker-supplied text gets interpreted as executable markup. Imagine a comment field that stores whatever someone types, then renders it straight into the page:
<div class="comment">Nice post, <script>steal()</script></div>Without escaping, that script runs for every visitor. Escape the input and the browser shows the literal text instead of executing it. Most modern template engines (React, Vue, Angular, Jinja2, ERB with the right helpers) escape by default — but the moment you reach for dangerouslySetInnerHTML, v-html, or string concatenation, that safety net disappears and you're on your own.
Displaying code and markup
The other common case is harmless: you want to show HTML as text. Documentation sites, code examples, blog posts about escaping HTML — this very paragraph needs its angle brackets escaped so you can read them rather than have them vanish into the DOM.
A short worked example
Say you're building a search results page that echoes the query back to the user. Here's the naive version in Node:
app.get('/search', (req, res) => {
const q = req.query.q;
res.send(`<p>Results for: ${q}</p>`);
});Hit that with ?q=<img src=x onerror=alert(1)> and you've got a working XSS. The fix is a tiny escape function:
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
app.get('/search', (req, res) => {
const q = escapeHtml(req.query.q || '');
res.send(`<p>Results for: ${q}</p>`);
});Now the input renders as plain text. Note the ordering — ampersand gets escaped before everything else, exactly as I warned above.
Common gotchas
Context matters more than you think
HTML escaping protects HTML body content. It does not make you safe everywhere. Data inside an attribute, inside a <script> block, inside a URL, or inside CSS all need different escaping rules. For example, putting unescaped quotes inside an unquoted attribute can break out of it entirely. Always quote your attributes, and escape for the specific context you're writing into.
Double escaping
If your framework already escapes output and you escape again manually, users see &lt; littered through the page. The reverse is just as common: decoding something that was never encoded. Pick one layer to be responsible for escaping and stick to it.
Escaping when you should be sanitizing
Sometimes you genuinely need to render user-supplied HTML — a rich text editor, say. Escaping would strip all formatting. In that case you want sanitization (a library like DOMPurify that removes dangerous tags and attributes while keeping safe markup), not escaping. The two solve different problems; don't confuse them.
JSON embedded in HTML
Dropping a JSON blob into a <script> tag is a classic trap. A value containing </script> will close the tag early. Escape the forward slash in </ (write it as <\/) or encode the whole thing properly before embedding it.
Do it by hand or use a tool
For a quick one-off — checking what a string looks like escaped, cleaning up a snippet for documentation, or sanity-checking what a template produced — a small utility beats writing throwaway code. Our HTML Escape Tool handles both escaping and unescaping, which is handy when you're debugging why something rendered wrong and need to see the raw characters.
In your actual codebase, lean on your framework's built-in escaping and well-tested libraries rather than hand-rolling. The five-character escapeHtml above is fine for illustration, but production escaping needs to account for context and edge cases that a mature library already handles.
The takeaway
Treat all external data as hostile until proven otherwise. Escape it in the right context, let your framework do the heavy lifting where it can, and reach for sanitization — not escaping — when you actually need to render rich HTML. Get these habits right and a whole category of bugs and vulnerabilities simply stops happening.
Photo by Florian Olivo on Unsplash