If you've ever rendered a user's comment and watched half your layout disappear because someone typed <div>, you've met the problem that HTML escaping solves. It's unglamorous work, but getting it wrong is how you end up with broken markup or, worse, a cross-site scripting hole.

What escaping actually does

HTML has a handful of characters that mean something special to the parser. When you want those characters to show up as literal text instead of being interpreted as markup, you replace them with entities — the &name; or &#number; notation the browser decodes back into the original character.

The core set you care about most of the time is small:

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

That's the lot for most contexts. Everything else — accented letters, emoji, maths symbols — is fine to leave as UTF-8 as long as your page declares the right charset. You don't need to escape those for safety; escaping them is a legacy habit from the days of dodgy encoding support.

When you need it

The rule of thumb: escape any data that didn't come from you at the moment you insert it into HTML. That covers a lot of ground.

Rendering user-supplied text

Comments, usernames, search terms, form values echoed back into the page — all of it. If a user types <script>alert(1)</script> and you drop that straight into the DOM, you've handed them script execution on your origin. Escaping turns it into harmless visible text.

Displaying code or markup as content

Any time you want to show HTML rather than render it — documentation, a tutorial, a snippet of config — you escape it first. This post itself relies on escaping to display those entity examples above.

Building attributes

Attribute values have their own hazards. A stray quote can break out of the attribute and inject new ones. Always escape quotes when you're interpolating into an attribute, and prefer quoting attributes consistently.

Context matters more than people think

Here's the part that catches experienced devs out: escaping is context-sensitive. HTML entity escaping protects you in HTML text and attribute contexts. It does not make you safe inside:

  • JavaScript — if you inject data into an inline <script> block, HTML escaping won't help. You need JS string escaping (or better, pass data via JSON.parse or a data attribute).
  • URLs — query parameters need URL encoding, not HTML entities.
  • CSS — injecting into a style context has its own escaping rules.

Reaching for the wrong escaper gives you a false sense of security. The question is always "what parser is going to read this string next?"

Let the framework do it

Modern templating engines escape by default, and you should lean on that. React escapes anything you put between JSX tags. Vue escapes mustache interpolations. Jinja2, ERB, Handlebars, Go templates — all escape output unless you explicitly opt out.

The danger zones are the opt-out APIs: dangerouslySetInnerHTML, v-html, {{{ triple-stache }}}, innerHTML, and the | safe filter. The moment you use one of those, escaping is back on you — and if the content came from a user, you need sanitisation (a library like DOMPurify), not just escaping.

A worked example

Say you're building a tiny server-rendered comment list in plain Node without a template engine. Here's a minimal, correct escaper:

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

const comment = `<img src=x onerror="alert('xss')">`;

const html = `<li class="comment">${escapeHtml(comment)}</li>`;
// <li class="comment">&lt;img src=x onerror=&quot;...&quot;&gt;</li>

Notice the order: ampersand first. If you replace < with &lt; before escaping ampersands, a later & pass will turn your &lt; into &amp;lt; and double-escape everything. This is the single most common escaping bug I see.

On the display side, the browser receives &lt;img ... and renders it as the literal text <img .... No image request, no onerror, no script. That's the whole point.

Common gotchas

  • Double escaping. Escaping already-escaped content produces visible &amp; and &lt; gibberish. It usually happens when two layers both try to be helpful. Escape once, at the output boundary.
  • Escaping on input instead of output. Store the raw value; escape when you render. If you escape on the way in, you'll fight double-escaping forever and your data will be wrong for non-HTML consumers like APIs and CSVs.
  • Forgetting attribute quotes. Unquoted attributes can be broken out of with a space or >. Quote everything and escape the quote character.
  • Assuming HTML escaping covers JS. It doesn't. Different context, different rules.
  • Escaping when you should sanitise. If you genuinely need to render user-authored rich HTML, escaping destroys the formatting. Sanitise with an allowlist-based library instead.

A quick way to check your work

When I'm debugging encoding issues or just need to paste a snippet into a doc, I don't trust myself to escape by hand. Paste the text into our HTML Escape Tool and you get the escaped output instantly — handy for sanity-checking what the browser will actually see, or for grabbing a safe string to drop into a template.

The short version

Escape untrusted data at the point it enters an HTML context, use your framework's default escaping, and know which contexts entity escaping does and doesn't cover. Escape ampersands first, escape once, and reach for a sanitiser when you actually need to keep the markup. Do that consistently and an entire category of rendering bugs and injection attacks simply stops happening.

Photo by Florian Olivo on Unsplash