Splitting a query string on & and = and decoding the pieces by hand is a classic source of bugs: plus signs, missing values, repeated keys and malformed escapes all go wrong. JavaScript has had a standard answer for years. URLSearchParams and the URL object are available in every current browser and, as globals, in Node.js. This guide covers the whole API, the encoding rules it follows, and the behaviours that surprise people.
Every output below was produced by running the code when the page was built.
Creating a URLSearchParams
The constructor accepts a query string, an object, or a list of pairs:
new URLSearchParams("?q=shoes&size=42").toString()
// "q=shoes&size=42"
new URLSearchParams({ q: "a b&c", n: "1" }).toString()
// "q=a+b%26c&n=1"
new URLSearchParams([["t", "x"], ["t", "y"]]).toString()
// "t=x&t=y"A leading ? is ignored, so location.search can be passed directly. Only the list form can express a repeated key; an object cannot hold the same key twice.
Usually you do not construct one yourself. Every URL object has a live searchParams property, and changing it updates the URL:
const url = new URL("https://example.com/?x=1");
url.searchParams.append("q", "a b");
url.searchParams.delete("x");
url.href
// "https://example.com/?q=a+b"Reading values
const p = new URLSearchParams("a=1&a=0&b=2&c=");
p.get("a")
// "1"
p.getAll("a")
// ["1","0"]
p.get("c")
// ""
p.get("missing")
// null
p.has("b")
// true
p.size
// 4
[...p]
// [["a","1"],["a","0"],["b","2"],["c",""]]Three details decide whether your code is correct:
get()returns only the first value for a key. UsegetAll()wherever a key can repeat, such as filters and multi-selects.- A missing key returns
null; a key with an empty value returns"". Test withhas()or=== null, not with a truthiness check, or?c=and nocat all look the same. sizecounts pairs, not distinct keys, so repeated keys count more than once. It is a newer addition; check support if you target old browsers.
Writing values
const p = new URLSearchParams();
p.append("a", "1");
p.append("a", "2");
p.toString()
// "a=1&a=2"
p.set("a", "3");
p.toString()
// "a=3"
const q = new URLSearchParams("c=0&a=1&b=2&a=0");
q.sort();
q.toString()
// "a=1&a=0&b=2&c=0"set() removes every existing value for the key. sort() orders by key and is stable, so repeated keys keep their relative order. Sorting is useful for cache keys and for comparing two URLs that list the same parameters in a different order.
How it encodes: form rules, not encodeURIComponent
URLSearchParams serializes with the application/x-www-form-urlencoded rules from the WHATWG URL Standard. They are close to encodeURIComponent but not identical:
new URLSearchParams({ q: "a b&c=d/e?f~g*h!(i)'j" }).toString()
// "q=a+b%26c%3Dd%2Fe%3Ff%7Eg*h%21%28i%29%27j"
"q=" + encodeURIComponent("a b&c=d/e?f~g*h!(i)'j")
// "q=a%20b%26c%3Dd%2Fe%3Ff~g*h!(i)'j"- A space becomes
+, not%20. Every query parser reads it as a space; the space guide covers where that distinction matters. - It also encodes
~ ! ' ( ), whichencodeURIComponentkeeps. Only letters, digits and* - . _are left as they are. - A literal
+in a value is encoded as%2B, so it survives the round trip.
Both outputs are valid and decode to the same value. The difference only matters if something compares encoded strings exactly, such as a signature check.
How it decodes
new URLSearchParams("q=a+b").get("q")
// "a b"
new URLSearchParams("q=a%20b").get("q")
// "a b"
new URLSearchParams("q=a%2Bb").get("q")
// "a+b"
new URLSearchParams("q=100%").get("q")
// "100%"
new URLSearchParams("q=caf%E9").get("q")
// "caf�"
new URLSearchParams("a=1&b").get("b")
// ""Unlike decodeURIComponent, it never throws. A stray % is kept, and bytes that are not valid UTF-8 become �. That makes it safe for untrusted input, but it also means a Latin-1 value is silently damaged. If you need to detect that, see URI malformed. A key without = is read as an empty value.
Pitfalls
Object.fromEntries drops repeated keys
Object.fromEntries(new URLSearchParams("t=x&t=y"))
// {"t":"y"}Only the last value survives. When a key can repeat, build the object yourself:
const p = new URLSearchParams("t=x&t=y&q=1");
Object.fromEntries([...new Set(p.keys())].map((k) => {
const all = p.getAll(k);
return [k, all.length > 1 ? all : all[0]];
}))
// {"t":["x","y"],"q":"1"}The Query String Parser uses the same rule for its Copy as JSON button.
Objects and arrays are turned into strings
new URLSearchParams({ t: ["x", "y"] }).toString()
// "t=x%2Cy"
new URLSearchParams({ a: { b: 1 } }).toString()
// "a=%5Bobject+Object%5D"There is no standard way to put nested data in a query string. Conventions such as a[b]=1 or t[]=x belong to particular frameworks, so append each array item under the same key, and send complex data as JSON in a request body instead.
Two ways to set the query, two encodings
const u = new URL("https://example.com/");
u.searchParams.set("q", "a b");
u.href
// "https://example.com/?q=a+b"
u.search = "q=a b&c=d";
u.href
// "https://example.com/?q=a%20b&c=d"Assigning search takes your string as the query and only encodes characters that are not allowed, so a space becomes %20 and an & in your text still splits parameters. Use searchParams for values; use search only for a query string you already built.
The URL object
URL parses and builds whole addresses with the same rules browsers use. Each setter encodes for its own part of the URL:
const u = new URL("https://example.com");
u.pathname = "/a b/é";
u.hash = "a b";
u.href
// "https://example.com/a%20b/%C3%A9#a%20b"
u.username = "a@b";
u.password = "p:w";
u.href
// "https://a%40b:p%3Aw@example.com/"
new URL("../b?x=1", "https://example.com/a/c/d").href
// "https://example.com/a/b?x=1"The user name and password setters encode @ and :, which is exactly what connection strings need; see passwords in URLs. The two-argument form resolves a relative link against a base, the same way a browser resolves an href.
Invalid URLs throw
new URL("/relative/path")
// TypeError: Invalid URL
new URL("https://exa mple.com")
// TypeError: Invalid URLA relative path needs a base, and a host may not contain a space. Wrap new URL() in try/catch when the input comes from a user, or check first with URL.canParse(input), which returns true or false. URL.canParse is newer than the rest of the API, so check browser support if you target older browsers. The URL Parser shows how any address splits into these parts, and warns about hosts like the one above.
On the server
In Node.js, URL and URLSearchParams are globals, so the same code runs on both sides. Many frameworks parse query strings with their own libraries that support nested keys; their output can differ from URLSearchParams for repeated and bracketed keys, so test with the real framework.
Other languages have equivalents with the same form rules:
- Python:
urllib.parse.parse_qs('q=a+b%2Bc')returns{'q': ['a b+c']}, always as lists, so repeated keys are kept.urlencodebuilds a query and writes spaces as+. - C#:
System.Web.HttpUtility.ParseQueryStringreturns a collection that keeps repeated keys, andWebUtility.UrlEncodewrites spaces as+.
Summary
- Read with
url.searchParams.get(), andgetAll()for keys that repeat. - Write with
set()orappend(); never concatenate query strings by hand. - Expect
+for spaces in the output; it is correct. - Do not use
Object.fromEntrieswhen keys can repeat. - Wrap
new URL()intry/catchfor user input.