BBizKit

url.normalize

v0.1.0 latest

Normalize a URL string via the WHATWG URL parser for spec-compliant canonicalization.

urlnormalizationwhatwgcanonicalizationdeduplication

Normalize a URL string via the WHATWG URL parser for spec-compliant canonicalization.

Signature

function normalize(url: string): string | null

Problem

URLs from different sources vary in scheme casing, port inclusion, path resolution, and percent-encoding. Direct string comparison fails for semantically identical URLs, causing cache fragmentation and incorrect deduplication.

How It Works

Delegates to globalThis.URL for WHATWG-compliant normalization: scheme lowercasing, percent-encoding normalization, default port removal, and path resolution.

Boundaries

  • Returns null for invalid URLs (no exception thrown).
  • Returns null for empty/whitespace input.
  • Throws TypeError for non-string input.
  • Requires a runtime with globalThis.URL (available in all modern JS environments).

Replaces

Common boilerplate this function replaces:

try { return new URL(input).toString(); } catch { return null; }

Examples

url.normalize("HTTP://Example.COM/path/../other");  // "http://example.com/other"
url.normalize("not a url");  // null
url.normalize("");  // null

Standards

Caveats

  • Relies on the platform's URL implementation for normalization behavior.
  • Relative URLs without a base are invalid and return null.

FAQ

How to normalize a URL in JavaScript?

url.normalize('HTTP://Example.COM/') returns 'http://example.com/'. Uses WHATWG URL parser for spec-compliant normalization.

What happens with an invalid URL?

Returns null instead of throwing an exception.

Does url.normalize resolve relative paths?

Yes. url.normalize('http://example.com/a/../b') resolves to 'http://example.com/b'.

Can url.normalize handle relative URLs?

No. Relative URLs without a scheme are invalid per WHATWG and return null.

Does url.normalize remove default ports?

Yes. The WHATWG URL parser removes default ports (e.g. :443 for https, :80 for http).