URLSearchParamsLoading saved progress…

URLSearchParams

URLSearchParams is the browser's helper for reading and building query strings — the ?a=1&b=2 part of a URL. It parses that encoded text into name/value pairs and gives you methods to read, add, replace, and serialize them, handling the URL encoding so you don't have to.

Implement a URLSearchParamsLite class. Its constructor takes a query string (with an optional leading ?) and parses it into pairs, decoding %xx escapes and treating + as a space. Then support get, getAll, has, append, set, delete, and toString.

Signature

class URLSearchParamsLite {
  constructor(init) {}
  get(name) {}      // first value, or null
  getAll(name) {}   // array of all values
  has(name) {}      // boolean
  append(name, value) {} // add a pair (duplicates allowed)
  set(name, value) {}    // replace all pairs for name with one
  delete(name) {}        // remove all pairs for name
  toString() {}          // encoded query string
}

Examples

const p = new URLSearchParamsLite('a=1&a=2&b=3');
p.get('a');    // '1'   — the first value
p.getAll('a'); // ['1', '2']
p.has('b');    // true
p.append('a', '4');       // a is now ['1', '2', '4']
p.set('a', '9');          // a is now ['9'] — all replaced by one
p.toString();             // 'a=9&b=3'
new URLSearchParamsLite('q=hello+world').get('q'); // 'hello world'

Notes

  • A name can repeata=1&a=2 is two pairs. get returns the first; getAll returns all.
  • get on a missing name is null — not undefined; getAll returns [].
  • set collapses duplicates — it replaces every pair for the name with a single one (appending if absent).
  • Decode on parse%xx escapes are decoded and + becomes a space.
  • Encode on toString — a space becomes +, and reserved characters (&, =, …) are percent-encoded, so the output round-trips.
  • Order is preserved — pairs keep their insertion order in toString.
Loading editor…