All articles

Escaping HTML in JavaScript to prevent XSS

· 3 min read

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
& &amp; Starts an entity; must be escaped first
< &lt; Starts a tag
> &gt; Ends a tag
" &quot; Ends a double-quoted attribute
' &#39; Ends a single-quoted attribute

A correct escape function

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

escapeHtml('<img src=x onerror="alert(1)">');
// '&lt;img src=x onerror=&quot;alert(1)&quot;&gt;'

The order matters: replacing & last would turn &lt; into &amp;lt;. A single pass with a lookup table avoids the problem entirely:

const entities = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
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 &amp; Jerry &lt;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

  1. Render user text with textContent or framework interpolation.
  2. When you must build HTML strings, escape & < > " ', and quote every attribute.
  3. Validate URL schemes for href and src.
  4. Embed data for scripts as JSON with < escaped.
  5. Sanitize, don't escape, when users may submit HTML.
  6. Add a Content Security Policy as a safety net.

Converting markup for React has its own rules; see HTML vs JSX.

Frequently asked questions

Do I need to escape HTML in React?

Not for values rendered in JSX: React escapes text automatically. You do need care with dangerouslySetInnerHTML, and with href values, because React doesn't block every javascript: URL in all versions.

Should I escape on input or on output?

On output, for the context you're writing into. Store the original text, and escape it when rendering it as HTML, putting it in a URL or embedding it in JSON.

Is ' or ' better for single quotes?

Both work in HTML5. &#39; also works in old HTML4 parsers, which is why many libraries use it.

Do I need to escape > ?

Not strictly in text content, but escaping it costs nothing and avoids problems in edge cases, so most escape functions include it.

Further reading