Skip to curriculum
Jump to the editor

18.1. URLSearchParams from scratch

Medium
Topics
25–40 min

Every filter, search box and paginated list keeps its state in the query string: ?q=café&tag=new&tag=sale&page=2. Reading it by hand with split("=") works until a value holds a +, a %, an = or an accented letter. The browser's URLSearchParams follows exact rules for all of these (the application/x-www-form-urlencoded format).

Write a SearchParams class in search-params.js that reads and writes query strings with the same rules as the built-in, for every case in the requirements below.

Signature

JAVASCRIPT
class SearchParams {
  constructor(init)      // init: a query string, with or without "?"; missing means empty
  get(name)              // the first value for name, or null
  getAll(name)           // an array of every value for name, in order
  has(name)              // true or false
  append(name, value)    // adds a pair at the end
  set(name, value)       // replaces, see requirement 12
  delete(name)           // removes every pair with that name
  toString()             // the pairs as a query string, without "?"
}

Requirements

  1. The constructor removes one leading ? (only one), splits the rest at &, and skips empty pieces.
  2. Each piece splits at its first =: the name is before it, the value after it. A piece without = has the value "".
  3. + in a name or value decodes to a space; %2B decodes to +.
  4. % followed by two hex digits decodes to that byte; the bytes are read as UTF-8 (%C3%A9 is é).
  5. A % that is not followed by two hex digits stays as it is (%zz, %4, a final %). Nothing throws.
  6. Bytes that are not valid UTF-8 become U+FFFD; a byte order mark at the start of a name or value is kept.
  7. get returns the first value or null. getAll returns a new array every call ([] when the name is missing).
  8. toString writes name=value pairs joined by &, in order, a missing value as name=.
  9. In toString, a space becomes +; letters, digits and * - . _ stay; every other byte of the UTF-8 encoding becomes %XX with upper-case hex.
  10. Names and values are converted with String(); a lone surrogate becomes U+FFFD.
  11. append adds at the end and keeps duplicates.
  12. set gives the first pair with the name the new value, in its place, and removes the other pairs with that name; with no such pair, it appends.
  13. delete removes every pair with the name; has says whether one is left.
  14. Parsing the output of toString gives back the same pairs.
  15. It does not use the built-in URLSearchParams or URL.

Examples

JAVASCRIPT
const params = new SearchParams("?q=caf%C3%A9+au+lait&tag=new&tag=sale&flag");
params.get("q");        // "café au lait"
params.getAll("tag");   // ["new", "sale"]
params.get("flag");     // ""
params.get("page");     // null
JAVASCRIPT
const params = new SearchParams("a=1&b=2&a=3");
params.set("a", "x y");
params.append("c", "50%");
params.toString();      // "a=x+y&b=2&c=50%25"
JAVASCRIPT
new SearchParams("x=100%&y=%zz&z=1=2").get("x");   // "100%"  (not an error)
new SearchParams("z=1=2").get("z");                 // "1=2"
new SearchParams().toString();                      // ""

Environment

  • Plain JavaScript in a browser page; the tests create new SearchParams(…) from search-params.js and compare every result with the browser's own URLSearchParams.
  • Not allowed: URLSearchParams and URL (a test removes them while it runs). TextEncoder, TextDecoder, encodeURIComponent and string methods are fine.
  • Out of scope: building from an object or an array of pairs, sort, size, iteration (entries, forEach).

Hints

  1. A query can hold é as %C3%A9: two escapes for one character. At what level, characters or bytes, should the decoding happen?
  2. If you replace + after percent-decoding, what happens to a value that was %2B?
  3. encodeURIComponent is close for toString. Which characters does it treat differently?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…