Parse, edit, and serialize URL query strings in a class
A filter panel on a product listing page keeps its state in the URL query string. Build a small class, QueryParams, that parses a query string into an ordered list of name/value pairs, lets you edit that list, and serializes it back.
const params = new QueryParams(init?); // init is a string, default ''
init starts with ?, ignore that one character.&. Skip empty segments ('a=1&&b=2' has two pairs).=. A segment without = has the value ''. 'a==b' has the name 'a' and the value '=b', and '=x' has the name '' and the value 'x'.+ with a space, then apply decodeURIComponent. You may assume percent-escapes in the input are valid.size (getter): the number of pairs.get(name): the value of the first pair with that name, or null.getAll(name): a new array with every value for that name, in order ([] if none).has(name, value?): true if a pair has that name. If value is given, the pair must also have that value.append(name, value): add a pair at the end. Convert both arguments with String().set(name, value): if pairs with that name exist, change the value of the first one in place and remove the others. Otherwise append a new pair. Convert both arguments with String().delete(name, value?): remove every pair with that name. If value is given, remove only pairs with that name and that value.sort(): sort pairs by name, comparing strings with <. Pairs with the same name keep their relative order.toString(): join pairs as name=value with &, with no leading ?. Encode names and values with encodeURIComponent, then replace every %20 with +. No pairs gives ''.append, set, delete and sort return undefined.
const params = new QueryParams('?brand=acme&size=m&brand=zenit&q=rain+jacket');
params.get('brand'); // => 'acme'
params.getAll('brand'); // => ['acme', 'zenit']
params.get('q'); // => 'rain jacket'
params.get('color'); // => null
params.size; // => 4
params.set('brand', 'nordwand');
params.toString(); // => 'brand=nordwand&size=m&q=rain+jacket'
params.append('price', 50);
params.delete('size');
params.sort();
params.toString(); // => 'brand=nordwand&price=50&q=rain+jacket'
const search = new QueryParams();
search.append('q', 'shoes & socks');
search.toString(); // => 'q=shoes+%26+socks'
Do not use the built-in URLSearchParams or URL.