Parse messy query strings into a read-only lookup class
A product listing page restores its filters from the address bar: ?brand=acme&brand=zest&q=running+shoes&sale. Links pasted from chat apps and old emails are often messy, with stray &s, half-encoded values, or a trailing #reviews, and the page must never crash on them.
Implement a class QueryReader that parses a query string once and answers read-only questions about it.
const query = new QueryReader(input);
query.get(name); // => first value, or null
query.getAll(name); // => every value for name, in order
query.has(name, value?); // => boolean
query.keys(); // => unique names, in first-seen order
query.entries(); // => [name, value] pairs, in order
query.size; // => number of pairs
query.toObject(); // => { name: value | value[] }
# onward. Then drop one leading ? if present.& and skip empty segments, so a=1&&b=2& has two pairs.=. A segment with no = has the value ''. =x has the name ''.+ with a space, then percent-decode with decodeURIComponent. If decoding throws (for example 100% or %E0%A4), keep the text with only the + replacement applied.first%20name=Ada answers get('first name').get(name): the first value for name, or null if there is none. An empty value returns '', not null.getAll(name): an array of every value for name, or [].has(name): whether any pair has that name. has(name, value): whether any pair has that name and that value.keys(): each name once, in the order it first appears.entries(): every [name, value] pair in order, including repeats.size: a getter for the number of pairs.toObject(): a plain object. A name that appears once maps to its string; a name that appears more than once maps to an array of its values.Every array and object you return is new, so changing it does not affect later calls.
const filters = new QueryReader('?brand=acme&brand=zest&q=running+shoes&sale#reviews');
filters.get('brand'); // => 'acme'
filters.getAll('brand'); // => ['acme', 'zest']
filters.get('q'); // => 'running shoes'
filters.get('sale'); // => ''
filters.get('color'); // => null
filters.has('brand', 'zest'); // => true
filters.keys(); // => ['brand', 'q', 'sale']
filters.size; // => 4
filters.toObject(); // => { brand: ['acme', 'zest'], q: 'running shoes', sale: '' }
const messy = new QueryReader('discount=100%&&city=S%C3%A3o+Paulo&expr=a=b=c');
messy.get('discount'); // => '100%'
messy.get('city'); // => 'São Paulo'
messy.get('expr'); // => 'a=b=c'
messy.entries(); // => [['discount', '100%'], ['city', 'São Paulo'], ['expr', 'a=b=c']]
URLSearchParams or URL.__proto__.