url.withQuery
v0.1.0 latestSet or merge query parameters on a URL string with three merge strategies per RFC 3986 §3.4.
Set or merge query parameters on a URL string with three merge strategies per RFC 3986 §3.4.
Signature
function withQuery(url: string, query: Record<string, unknown>, opt?: WithQueryOptions): string
Type Definitions:
WithQueryOptions— interface
Problem
Adding or replacing query parameters on an existing URL requires parsing the existing query string, merging new parameters, and re-serializing — a multi-step process repeated in every URL manipulation. Different merge semantics (replace, keep, append) are needed in different contexts.
How It Works
Provides three merge strategies: replace (default) replaces the entire query string, keep only adds keys not already present, append adds all new parameters. Fragment is stripped. Uses RFC 3986 encoding.
Boundaries
- Throws TypeError for non-string URL.
- Fragment (#...) is removed from the output.
- Uses RFC 3986 encoding (%20 for space).
- null/undefined values are omitted from the output.
Replaces
Common boilerplate this function replaces:
const [base, qs] = url.split('?'); const params = new URLSearchParams(qs); Object.entries(newQuery).forEach(([k, v]) => params.set(k, v)); return base + '?' + params.toString();
Examples
url.withQuery("https://example.com?a=1", { b: "2" }); // "https://example.com?b=2"
url.withQuery("https://example.com?a=1", { b: "2" }, { queryMerge: "append" }); // "https://example.com?a=1&b=2"
url.withQuery("https://example.com?a=1", { a: "2" }, { queryMerge: "keep" }); // "https://example.com?a=1"
Standards
Caveats
- Default mode is 'replace', which discards existing query parameters entirely.
- Fragment is always stripped from the output, regardless of merge mode.
FAQ
How to add query parameters to a URL without removing existing ones?
Use url.withQuery(url, params, { queryMerge: 'append' }) to append new parameters while keeping existing ones.
How to replace all query parameters on a URL?
url.withQuery(url, newParams) replaces the entire query string by default (replace mode).
How to add a parameter only if it doesn't already exist?
Use url.withQuery(url, params, { queryMerge: 'keep' }). Existing keys are preserved.
Does url.withQuery preserve URL fragments?
No. The fragment (#...) is always stripped from the output.
What encoding does url.withQuery use?
RFC 3986 encoding (%20 for spaces), not WHATWG form encoding (+ for spaces).