A query string holds optional key-value parameters after `?`, describing which variation of a view is shown rather than identifying a different resource. Use it for state that should survive reloads or be shared and bookmarked, such as filters, sorting, pagination, and search. The path identifies the resource; the hash points to a fragment within the document. section 10.1.8 section 10.1.9
Keep query-string behavior predictable:
- Set defaults for parameters and remove default values when useful to keep URLs clean. section 10.1.11
- Sort parameters when canonical URLs matter; consistent ordering can help caching and analytics deduplication. section 10.1.11
- Replace the current history entry for small state normalization; add an entry when users would expect Back to undo the change. section 10.1.11
const url = new URL(location.href);
url.searchParams.set("sort", "price");
url.searchParams.set("view", "grid");
if (url.searchParams.get("page") === "1") {
url.searchParams.delete("page");
}
url.searchParams.sort();
history.replaceState(null, "", url);
This example updates sorting and view parameters, removes the default page, sorts the parameters, and replaces the current history entry. section 10.1.11
