Sanitize href URL (Block javascript: XSS)
Arguments
input: string —User-provided URL-ish string that you want to place into href.
Returns
string | null — Solution idea
Define the href contract before parsing: explicit http, https, mailto, and tel URLs are allowed; relative URLs must resolve to a reserved trusted origin; everything else returns null. Reject controls and backslashes before trimming or parsing so normalization cannot expose a dangerous scheme or reinterpret a relative path as another host.
sanitizeHrefUrl('javascript:alert(1)') // => null
sanitizeHrefUrl(' https://example.com ') // => 'https://example.com/'
sanitizeHrefUrl('/settings') // => '/settings'
sanitizeHrefUrl('mailto:hi@example.com') // => 'mailto:hi@example.com'Solution
Overview
Define the href contract before parsing: explicit http, https, mailto, and tel URLs are allowed; relative URLs must resolve to a reserved trusted origin; everything else returns null. Reject controls and backslashes before trimming or parsing so normalization cannot expose a dangerous scheme or reinterpret a relative path as another host.
Approach: Reject ambiguous input, then parse against an explicit policy
Steps:
1) Convert input to text, but reject raw ASCII controls and backslashes before trimming.
2) Trim outer whitespace and reject empty text, percent-encoded ASCII controls, and protocol-relative forms.
3) Detect whether the text begins with an explicit scheme.
4) Parse explicit URLs directly; resolve other text against a reserved HTTPS base.
5) Validate the final parsed protocol against http, https, mailto, and tel.
6) For relative input, also require the parsed origin and protocol to match the trusted base.
7) Return normalized href for explicit URLs, the trimmed spelling for valid relatives, or null on every failure.
Complexity: O(n) time and O(n) parser output space.
const ASCII_CONTROLS = /[\u0000-\u001F\u007F]/;
const ENCODED_ASCII_CONTROLS = /%(?:0[0-9A-F]|1[0-9A-F]|7F)/i;
const EXPLICIT_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:/;
const SAFE_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']);
const TRUSTED_BASE = new URL('https://frontendatlas.invalid/');
export default function sanitizeHrefUrl(input) {
if (input == null) return null;
const raw = String(input);
if (ASCII_CONTROLS.test(raw) || raw.includes('\\')) return null;
const value = raw.trim();
if (!value || ENCODED_ASCII_CONTROLS.test(value) || value.startsWith('//')) {
return null;
}
const isExplicit = EXPLICIT_SCHEME.test(value);
try {
const parsed = isExplicit ? new URL(value) : new URL(value, TRUSTED_BASE);
if (!SAFE_SCHEMES.has(parsed.protocol)) return null;
if (!isExplicit) {
if (parsed.protocol !== TRUSTED_BASE.protocol || parsed.origin !== TRUSTED_BASE.origin) {
return null;
}
return value;
}
return parsed.href;
} catch {
return null;
}
}
const ASCII_CONTROLS = /[\u0000-\u001F\u007F]/;
const ENCODED_ASCII_CONTROLS = /%(?:0[0-9A-F]|1[0-9A-F]|7F)/i;
const EXPLICIT_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:/;
const SAFE_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']);
const TRUSTED_BASE = new URL('https://frontendatlas.invalid/');
export default function sanitizeHrefUrl(input: string): string | null {
if (input == null) return null;
const raw = String(input);
if (ASCII_CONTROLS.test(raw) || raw.includes('\\')) return null;
const value = raw.trim();
if (!value || ENCODED_ASCII_CONTROLS.test(value) || value.startsWith('//')) {
return null;
}
const isExplicit = EXPLICIT_SCHEME.test(value);
try {
const parsed = isExplicit ? new URL(value) : new URL(value, TRUSTED_BASE);
if (!SAFE_SCHEMES.has(parsed.protocol)) return null;
if (!isExplicit) {
if (parsed.protocol !== TRUSTED_BASE.protocol || parsed.origin !== TRUSTED_BASE.origin) {
return null;
}
return value;
}
return parsed.href;
} catch {
return null;
}
}
Notes & Pitfalls
Escaping HTML is not enough for href: you must also validate protocols (javascript: is the classic bypass). Sanitization is context-specific: a value safe for href is not automatically safe for CSS url() or innerHTML. Protocol-relative URLs and backslashes can change origin under the browser's special-URL parsing rules, so this contract rejects them.
ASCII controls are rejected rather than removed; deleting one can expose whitespace that an earlier trim already missed. Percent-encoded ASCII controls and embedded backslashes are rejected anywhere in the input. Empty strings should return null to avoid creating broken links. Invalid http/https URLs should return null (URL() throws).
Allowlist safe schemes and block everything else. Reject ambiguous characters before applying ordinary outer-whitespace trimming. Validate the final parsed scheme, and enforce a trusted origin for every relative URL.
Common mistakes on this challenge
href sanitizer is allowing unsafe protocols or blocking safe URLs
Reject ambiguous bytes, then enforce scheme and origin policy on the browser-parsed URL. Reject raw or percent-encoded ASCII controls and any backslash instead of repairing input. Parse explicit URLs directly and relative input against the reserved trusted HTTPS base. Allowlist the final parsed scheme and require relative input to retain the trusted origin.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.