Scriptdrill

Level 3: Strings and dates Exercise 22 of 45 Pro

Parse a query string

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Parse a URL query string such as `"?page=2&tag=js&tag=web"` into an object of strings. The leading `?` is optional. `+` means a space and `%XX` escapes are decoded. A key without `=` gets `""`. Only the first `=` separates key from value. Empty pieces (as in `a=1&&b=2`) are skipped. A key that appears more than once maps to an array of its values in order.

What this exercise teaches

indexOf finds only the first =, so values may contain = signs. Replacing + before decoding matters because decodeURIComponent leaves + alone, and an encoded plus (%2B) must survive as a literal +.

A hint if you get stuck

Split on `&`, and for each piece split at the first `=` with `indexOf`. Replace `+` with a space before `decodeURIComponent`. Collect repeats into an array.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Strings and dates