Sanitize href URL (Block javascript: XSS)

intermediate
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement sanitizeHrefUrl(input) for an <a href="..."> allowlist: explicit http, https, mailto, and tel URLs plus relative URLs that stay on a trusted origin. Return null for empty or malformed input, unknown schemes, protocol-relative URLs, ASCII controls (raw or percent-encoded), or any backslash. Reject dangerous input instead of repairing it.

Arguments

  • input: string — User-provided URL-ish string that you want to place into href.

Returns

string | null — A safe href string (normalized) or null if the input is unsafe.

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.

Examples
sanitizeHrefUrl('javascript:alert(1)') // => null

sanitizeHrefUrl('  https://example.com  ') // => 'https://example.com/'

sanitizeHrefUrl('/settings') // => '/settings'

sanitizeHrefUrl('mailto:hi@example.com') // => 'mailto:hi@example.com'