Every developer hits this eventually. You render some user-supplied text, and instead of showing <b>hi</b> literally, the browser bolds it — or worse, runs a <script> tag someone slipped in. The fix is HTML escaping, and understanding it properly saves you from both cosmetic bugs and genuine security holes.

What HTML escaping actually does

HTML has a handful of characters that mean something special to the parser. The most important are the angle brackets that open and close tags, and the ampersand that starts an entity. Escaping means replacing those characters with their entity equivalents so the browser treats them as plain text instead of markup.

The core five you care about:

  • & becomes &amp;
  • < becomes &lt;
  • > becomes &gt;
  • " becomes &quot;
  • ' becomes &#39; (or &apos; in XML/HTML5)

Escape the ampersand first, always. If you replace < with &lt; and then run an ampersand pass afterwards, you'll double-escape and turn &lt; into &amp;lt;. Order matters more than people expect.

When you need it

The rule of thumb: escape any data you didn't write yourself the moment it lands in HTML. That covers a lot of ground.

Rendering user content

Comments, usernames, product reviews, search queries echoed back on the results page — anything a user controls. If you drop it into the DOM without escaping, you've opened the door to cross-site scripting. Someone types <script>fetch('/steal?c='+document.cookie)</script> into a comment box and now it runs for every visitor.

Displaying code or markup as text

Documentation sites, tutorials, anything showing HTML snippets to readers. You want the literal tags visible, not interpreted. This is the non-security reason escaping exists, and it's just as common.

Building HTML strings in server code

If you're concatenating strings to produce HTML — in a template that doesn't auto-escape, or in a quick email generator — every interpolated value needs escaping first.

A worked example

Say you're logging a search query back onto the page. The naive version:

// DON'T do this
const query = req.query.q; // user controls this
res.send(`<p>Results for ${query}</p>`);

Pass ?q=<img src=x onerror=alert(1)> and the alert fires. Here's a small escape function and the safe version:

function escapeHtml(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

const query = req.query.q;
res.send(`<p>Results for ${escapeHtml(query)}</p>`);

Now the browser displays the raw text and nothing executes. Notice the ampersand replacement comes first in the chain — that ordering is deliberate.

Common gotchas

Escaping at the wrong boundary

Escaping is contextual. HTML body context needs the five characters above. But if you're writing into an HTML attribute, inside a <script> block, or into a URL, the rules differ. A value safe for body text can still break out of a poorly quoted attribute. Escape for the context you're writing into, not a generic one.

Double escaping

The classic. Your framework auto-escapes, then you escape again manually, and users see &amp;lt; on screen. Know whether your template engine already handles this. React, Vue, Angular, and most modern template systems escape by default — manually escaping on top of them is a bug, not extra safety.

Trusting the wrong escape for the job

HTML escaping is not URL encoding, and it's not SQL escaping. Each solves a different problem for a different parser. Using HTML entities to "sanitize" a database query does nothing useful. Match the escape to the sink.

Forgetting the quote characters

Plenty of hand-rolled escape functions handle <, >, and & but skip the quotes. That's fine for body text and dangerous in attributes. If the value ever ends up in <input value="...">, an unescaped quote lets an attacker close the attribute and add their own.

Rich text vs escaping

Escaping and sanitizing aren't the same. If you actually want users to submit some HTML — bold, links, lists — escaping everything defeats the purpose. There you need a sanitizer like DOMPurify that strips dangerous tags while keeping safe ones. Reach for escaping when the data should be plain text; reach for a sanitizer when it should be limited markup.

Decoding goes the other way

Sometimes you receive already-escaped content and need the original back — reading an RSS feed, parsing an API response, debugging a payload. Unescaping reverses the mapping: &lt; turns back into <. Just be careful about where that decoded output lands afterwards; decoding and then injecting into the DOM puts you right back at square one.

When to automate it

For one-off conversions — checking what a snippet looks like escaped, cleaning up copied markup, or prepping a code example for docs — a browser tool beats writing a script. Our HTML Escape Tool handles escaping and unescaping both directions, which is handy when you're staring at a tangled string and just want to see it clearly.

For anything in production, keep it in code. Use your framework's built-in escaping, understand the context you're rendering into, and only hand-roll an escape function when you genuinely have to. The five-character replacement above is correct for body text — but the moment your data moves into attributes, scripts, or URLs, stop and pick the right tool for that context. Most XSS bugs come down to someone escaping for the wrong boundary, not forgetting to escape at all.

Photo by Florian Olivo on Unsplash