Skip to content
jshacks.dev
Security

Escape HTML before inserting it into page

Replace the five special characters before putting user text in markup, or use textContent so the browser never parses it, to stop cross-site scripting.

1 min read
Summarize in AI

If you build HTML from user input with a template string, a name such as <img src=x onerror=alert(1)> becomes a live element. Escaping turns the special characters into harmless text.

escape.jsJavaScript
function escapeHtml(text) {
  return String(text)
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

const name = '<img src=x onerror=alert(1)>';
console.log(`<p>Hello, ${escapeHtml(name)}</p>`);
Text
<p>Hello, &lt;img src=x onerror=alert(1)&gt;</p>

The ampersand has to be replaced first, otherwise the & inside the later replacements would be escaped again. The browser shows the escaped text as plain characters, and the onerror handler never runs.

The better habit is to avoid building markup from strings at all: set element.textContent = name, which treats the value as text and needs no escaping. Escaping is correct only for text and quoted attribute values; it does not make a value safe inside a <script> block, an href that can start with javascript:, or an inline style. Use a template engine that escapes by default, and a sanitizer such as DOMPurify when you must allow some HTML. See the OWASP XSS prevention cheat sheet.

Taggedxss
Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.