← All Exercises

URL Normalization for Cache Keys

intermediatejavascript~20min

Background

CDN and crawler deduplication rely on URL normalization so that HTTP://Example.com:80/?b=2&a=1 and http://example.com/?a=1&b=2 share one cache entry.

Problem

Normalize each URL with these rules: lowercase the scheme and hostname, remove the default port (80 for http, 443 for https), sort query parameters by key then value, and drop the fragment. Output the normalized URL strings in input order.

Input

A JSON object {"urls": string[]} of absolute http or https URLs.

Output

A JSON object {"normalized": string[]} with one canonical URL per input.

Sample tests

Sample 1

Input: {"urls":["HTTP://Example.COM:80/a/b?b=2&a=1#frag","https://example.com:443/a/b/?z=1","http://example.com:8080/x?k=2&k=1"]}
Expected: {"normalized":["http://example.com/a/b?a=1&b=2","https://example.com/a/b/?z=1","http://example.com:8080/x?k=1&k=2"]}

Sample 2

Input: {"urls":["http://example.com/#top","http://example.com"]}
Expected: {"normalized":["http://example.com/","http://example.com/"]}

Your solution

Learning objective

Apply WHATWG URL parsing plus deterministic canonicalization rules.