Frontend interview practice question

Escaping vs Sanitizing: What's the Difference?

HighIntermediateJavascript

Interview quick answer

Escaping encodes characters so data renders as text in one output context; sanitizing filters HTML to an allowlist so some markup can stay. Validate input, escape output, sanitize only when you must render user HTML.

Interview focus

This JavaScript interview question tests whether you can explain Escaping vs sanitizing: what is the difference, connect it to production trade-offs, and handle common follow-up questions.

  • Escaping vs sanitizing: what is the difference explanation without falling back to memorized definitions
  • Security and Html reasoning, edge cases, and production failure modes
  • How you would answer the most likely JavaScript interview follow-up
Practice more JavaScript interview questions
Interview answer drill

Use this JavaScript interview question to rehearse a quick answer, common mistake, follow-up, and production pitfall.

Full interview answer

Escaping and sanitizing both exist to stop untrusted data from being read as code, but they answer different questions. Escaping, also called output encoding, converts the characters that carry meaning in a given context, such as < and & in HTML, into a representation the browser shows as text. Sanitizing takes input that is supposed to contain HTML and removes everything outside an allowlist of tags and attributes, so some markup survives. Validation is the third, separate step: rejecting input that does not match the expected shape. The rule that holds up in production is to validate on the way in, escape on the way out for the exact context, and sanitize only where the product must render user-supplied HTML.

Aspect

Escaping (output encoding)

Sanitizing

Validation

Question it answers

How do I display this safely in this context?

Which parts of this HTML may stay?

Is this input the shape I expect?

Where it runs

At output, every time the value is rendered

Once, where HTML must be accepted or rendered

At input, before storing or processing

Input expectation

Plain text

HTML the product wants to keep

Anything

What happens to the data

Nothing is lost; characters are encoded for one context

Disallowed tags and attributes are dropped

The value is accepted or rejected

Context-specific

Yes: HTML body, attribute, URL, JavaScript and CSS each have their own rules

No, HTML only

No

Typical tools

textContent, setAttribute, encodeURIComponent, template auto-escaping

DOMPurify, setHTML, server-side allowlist libraries

Schema validators, format checks, type checks

Failure mode

The right encoder in the wrong context still leaves XSS

A weak allowlist lets XSS through; a strict one destroys content

Does nothing against valid but dangerous data, such as a bio that contains a script tag

Escaping, sanitizing and validation side by side

Escaping: the same string, five contexts

The browser reads the same characters differently depending on where you put them, so the encoder must match the destination. In the DOM the safest move is to use APIs that never parse markup at all.

JAVASCRIPT
const input = '<img src=x onerror="alert(1)">';

// HTML text: textContent never parses markup
el.textContent = input;

// HTML attribute: set it as a value, never by string concatenation
link.setAttribute('title', input);

// URL parameter: percent-encode the value, then check the protocol
const url = new URL(`/search?q=${encodeURIComponent(input)}`, location.origin);

// Data for a script: serialize to JSON into a data attribute, never into inline JavaScript
el.dataset.payload = JSON.stringify({ input });
                  

Context

Safe approach

What goes wrong

HTML body

textContent, or template interpolation that encodes &, <, >, " and '

innerHTML with concatenated strings runs whatever tags were injected

HTML attribute

setAttribute, or quoted attributes with encoded values

An unquoted attribute lets a space close it and add onerror

URL

encodeURIComponent on each parameter value, then allow only http: and https: after parsing with new URL()

javascript: and data: links survive HTML encoding untouched

JavaScript

Keep user data out of inline scripts and event handlers; pass it through JSON.stringify into a data attribute

Quote escaping by hand misses cases, and attribute encoding does not protect onclick

CSS

Allow only known values, or expose them through CSS custom properties set from JavaScript

User input inside style or url() can trigger requests or break out of the declaration

One value, five encoders

Sanitizing: keep some HTML, drop the rest

Sanitizing is for the cases where the product promises rich text: comments with bold and links, a CMS body, a markdown preview. The sanitizer parses the HTML, walks the tree and keeps only the tags and attributes on the allowlist, which is why a regex can never do the job. Use a maintained library and give it the smallest allowlist the feature needs.

JAVASCRIPT
import DOMPurify from 'dompurify';

const dirty = '<p>Hi <b>there</b><img src=x onerror="alert(1)"><a href="javascript:alert(2)">x</a></p>';

const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_TAGS: ['p', 'b', 'i', 'a'],
  ALLOWED_ATTR: ['href', 'rel', 'target']
});
// <p>Hi <b>there</b><a>x</a></p>  the img is gone and the javascript: href was removed

bioEl.innerHTML = clean;

// Where the browser supports it, the built-in sanitizer needs no library
if ('setHTML' in bioEl) bioEl.setHTML(dirty);
                  

Sanitize input or escape output?

The old advice was to sanitize everything on the way in. It fails for two reasons. Input does not know where it will be shown later, so one transformation cannot be right for the HTML body, an attribute, a URL and a JSON payload at once. And it destroys data: a user named O’Brien or a code snippet in a support ticket comes out mangled. The approach that holds up is to store the original, validate its shape at the boundary, escape it at every output for that output’s context, and reserve sanitizing for the one place where the feature is HTML itself. When you do sanitize rich text, keep the raw version too, re-sanitize when the allowlist changes, and never serialize the sanitized DOM back to a string and parse it again with innerHTML, because re-parsing can reopen holes the sanitizer closed. The DOM XSS sinks answer lists every API that parses markup, and the escape HTML exercise has you write the encoder by hand.

Framework

Escapes for you

Where it stops

React

Text and attribute values in JSX are encoded

dangerouslySetInnerHTML inserts raw HTML, so sanitize first; href values are not validated, so check URL protocols yourself

Angular

Interpolation and property bindings are sanitized by context, including [innerHTML] and [href]

bypassSecurityTrustHtml and its siblings switch that off for one value; direct DOM APIs are never covered

Vue

{{ }} and v-bind encode text and attributes

v-html inserts raw HTML and the docs say to sanitize first; see how Vue interpolates into the DOM

Plain DOM

Nothing

textContent and setAttribute are safe by construction; innerHTML, outerHTML, insertAdjacentHTML and document.write parse markup

Where frameworks escape for you, and where they stop

Defense in depth

  • Content Security Policy: a script-src without 'unsafe-inline' stops injected inline scripts and event handlers from running even when one escape is missed.
  • Trusted Types: with require-trusted-types-for 'script', passing a plain string to innerHTML or eval throws, so every sink has to go through a policy that sanitizes. Baseline across current browsers since early 2026.
  • setHTML: the built-in sanitizer always strips scripts and event handlers, but availability is still limited, so feature-detect it and fall back to a library.
  • Cookies: HttpOnly keeps the session cookie out of reach of an injected script, which limits the damage when everything else fails; see cookie options.

Mistakes interviewers look for

  • Stripping tags with a regex. HTML is not a regular language; <scr<script>ipt>, attribute tricks and malformed markup get through. A parser-based sanitizer is the only option.
  • Encoding for the wrong context. HTML-encoding a value and dropping it into href, an event handler or inline JavaScript leaves those contexts open.
  • Double encoding. Encoding by hand and then rendering through a template that encodes again shows the entity text itself to the user instead of the character. Encode once, at the output.
  • Sanitizing once and reusing the result everywhere. Sanitized HTML is safe in the HTML body; put it in an attribute or a URL and the rules change.
  • Storing only the sanitized version. When the allowlist tightens or a bypass is fixed, you cannot re-sanitize what you no longer have.
  • Trusting the wrong helper. escape() and encodeURI are not HTML encoders, and encodeURIComponent is for URL parameter values only.
  • Letting javascript: through. HTML encoding does nothing to a URL scheme; parse the URL and allow only the protocols you expect.
  • Calling validation sanitizing. Rejecting an email address with a bad shape is validation; it says nothing about a valid comment that contains <script>.

Interview follow-ups

What is the difference between validation and sanitization?

Validation decides whether input is acceptable and rejects it when it is not: wrong format, too long, unexpected type. Sanitization changes the input to make it safe to use, typically by removing disallowed HTML. Validation keeps bad data out, sanitization makes allowed data safe, and escaping makes any data safe to display.

What does it mean to sanitize input?

To transform untrusted input into a version that meets a safety rule, such as HTML reduced to an allowlist of tags. It only makes sense for data that is supposed to carry markup; for plain text, escaping at output is the right tool and sanitizing destroys legitimate characters.

What is escaping in HTML?

Replacing the five characters the HTML parser treats as syntax with their entities, so the browser shows them as text instead of reading them as tags or attribute boundaries:

HTML
&   becomes   &amp;
<   becomes   &lt;
>   becomes   &gt;
"   becomes   &quot;
'   becomes   &#x27;
                  

How do you sanitize a string in JavaScript?

If the string is text, you do not sanitize it: set it with textContent or bind it through your framework and the characters are encoded for you. If the string is HTML you intend to render, run it through DOMPurify with an explicit allowlist, or setHTML where the browser supports it, and assign the result to innerHTML.

Should you escape input or output?

Output. The same value can be rendered into HTML, an attribute, a URL and a JSON payload, and each needs a different encoder, so the encoding has to happen where the context is known. Validate at input, store the original, escape at output.

Can escaping and sanitizing be used together?

Yes, and real products do: sanitize the rich-text field once with an allowlist, escape every other field at output, and keep CSP and Trusted Types as the net underneath both.

Still so complicated?

Think of a club with a guest list:

  • Validation is the ticket check at the door: wrong ticket, no entry.
  • Sanitizing is the bouncer who lets guests in but takes away anything not on the allowed list.
  • Escaping is putting every guest’s words in quotation marks so nobody mistakes them for the DJ’s instructions.

The ticket check and the bouncer work at the entrance; the quotation marks are applied every time someone speaks.

Summary

  • Escaping encodes data for one output context so it renders as text; sanitizing filters HTML to an allowlist so some markup survives; validation accepts or rejects input by shape.
  • Validate at input, escape at output, sanitize only where the product renders user HTML, and store the original.
  • Every context has its own encoder: textContent for HTML text, setAttribute for attributes, encodeURIComponent plus a protocol check for URLs, JSON in data attributes for script data.
  • Never strip tags with a regex, never reuse sanitized HTML in another context, and never encode twice.
  • CSP, Trusted Types and HttpOnly cookies catch what the first line misses.

Guides
Preparing for interviews?

Built in public

The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.

Star on GitHub