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.
Frontend interview practice question
Escaping vs Sanitizing: What's the Difference?
Interview quick answer
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
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 |
| DOMPurify, | 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: 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.
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 |
|
|
HTML attribute |
| An unquoted attribute lets a space close it and add |
URL |
|
|
JavaScript | Keep user data out of inline scripts and event handlers; pass it through | Quote escaping by hand misses cases, and attribute encoding does not protect |
CSS | Allow only known values, or expose them through CSS custom properties set from JavaScript | User input inside |
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.
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 |
|
Angular | Interpolation and property bindings are sanitized by context, including |
|
Vue |
|
|
Plain DOM | Nothing |
|
Defense in depth
- Content Security Policy: a
script-srcwithout'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 toinnerHTMLorevalthrows, 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:
HttpOnlykeeps 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()andencodeURIare not HTML encoders, andencodeURIComponentis 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:
& becomes &
< becomes <
> becomes >
" becomes "
' becomes '
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:
textContentfor HTML text,setAttributefor attributes,encodeURIComponentplus 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
HttpOnlycookies catch what the first line misses.
Use this as one explanation rep, then continue with the JavaScript interview questions cluster or a guided prep path.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.