Build and Parse URL Query Strings
Learn how to construct URL query strings from key-value pairs, handle special characters, work with array parameters, and use the URLSearchParams API for robust query string management.
Detailed Explanation
URL Query Strings
The query string is the part of a URL that carries key-value data, starting with ? and using & to separate multiple parameters.
Basic Syntax
https://search.example.com/results?q=javascript+tutorial&page=2&lang=en
\___________________/ \_____/ \_____/
| | |
parameter 1 param 2 param 3
URLSearchParams API
The modern way to work with query strings in JavaScript:
// Building
const params = new URLSearchParams();
params.append("q", "hello world");
params.append("page", "1");
params.append("tags", "js");
params.append("tags", "web");
console.log(params.toString());
// "q=hello+world&page=1&tags=js&tags=web"
// Parsing
const search = new URLSearchParams("?q=test&page=2");
console.log(search.get("q")); // "test"
console.log(search.get("page")); // "2"
console.log(search.has("q")); // true
Array Parameters
Different conventions exist for passing arrays:
// Repeated keys (URLSearchParams default)
?tags=js&tags=css&tags=html
// Bracket notation (PHP, Rails)
?tags[]=js&tags[]=css&tags[]=html
// Comma-separated (some REST APIs)
?tags=js,css,html
// Indexed (rare)
?tags[0]=js&tags[1]=css&tags[2]=html
Encoding Rules
Query string values must be percent-encoded for special characters:
| Character | Encoded | Notes |
|---|---|---|
| Space | + or %20 |
+ is standard in query strings |
& |
%26 |
Otherwise treated as separator |
= |
%3D |
Otherwise treated as key-value delimiter |
# |
%23 |
Otherwise starts a hash fragment |
% |
%25 |
Escape the escape character itself |
Parameter Ordering
Query parameter order typically does not matter to servers, but some caching systems and signature algorithms (like AWS Signature V4) require canonical parameter ordering. Sorting parameters alphabetically is a common normalization technique.
Use Case
Building query strings is fundamental to frontend development. Search forms submit data as query parameters, pagination relies on page/offset parameters, and filter UIs need to serialize multiple filter values into the URL. Understanding query string construction is essential for building shareable, bookmarkable URLs in single-page applications.