URLSearchParams in JavaScript: Parse and Serialize
The URLSearchParams interface provides a built-in,
standard way to work with URL query strings in modern JavaScript
environments, including web browsers and Node.js. This article explains
what the API is, how to use it to parse query strings into accessible
values, how to modify existing parameters, and how to serialize
parameter objects back into standard URL-encoded strings.
What is the URLSearchParams API?
The URLSearchParams API defines utility methods to work
with the query string of a URL (the part after the ?).
Traditionally, developers parsed query strings by splitting strings on
?, &, and =, or by using
regular expressions. The URLSearchParams API eliminates the
need for manual parsing by handling parameter extraction, URL decoding,
and URL encoding automatically.
Creating a URLSearchParams Instance
You can initialize a URLSearchParams object by passing a
query string, an object, an array of key-value pairs, or directly via
the URL object.
From a Query String
// Leading '?' is automatically handled and stripped
const params = new URLSearchParams('?product=laptop&category=tech&page=2');From an Object
const params = new URLSearchParams({
search: 'javascript',
sort: 'desc'
});From an Array of Pairs
const params = new URLSearchParams([
['filter', 'active'],
['filter', 'pending']
]);Directly from a URL Object
const url = new URL('https://example.com/api?user=john&status=active');
const params = url.searchParams; // URLSearchParams instanceParsing Query Strings
Once initialized, URLSearchParams provides methods to
read and inspect parameters without manual decoding.
1. Getting Single Values:
get()
The get() method returns the first value associated with
the given search parameter, or null if the parameter does
not exist.
const params = new URLSearchParams('name=Alice+Smith&role=admin');
console.log(params.get('name')); // "Alice Smith" (automatically decoded)
console.log(params.get('age')); // null2. Getting Multiple Values:
getAll()
If a query string contains duplicate keys (such as
tag=css&tag=html), the getAll() method
returns all values in an array.
const params = new URLSearchParams('tag=javascript&tag=webdev&tag=frontend');
console.log(params.getAll('tag')); // ['javascript', 'webdev', 'frontend']3. Checking Existence:
has()
The has() method checks whether a specific query
parameter exists.
const params = new URLSearchParams('status=active');
console.log(params.has('status')); // true
console.log(params.has('page')); // false4. Iterating Over Parameters
URLSearchParams implements the iterable protocol,
allowing iteration via for...of, forEach(),
keys(), values(), and
entries().
const params = new URLSearchParams('a=1&b=2&c=3');
for (const [key, value] of params.entries()) {
console.log(`${key}: ${value}`);
}Modifying and Serializing Query Strings
URLSearchParams provides methods to mutate parameters
and serialize them back into an encoded string.
Modifying Parameters
append(name, value): Appends a new key-value pair, preserving existing keys with the same name.set(name, value): Sets the value for a key. If the key already exists, it overwrites the value and removes duplicates.delete(name): Deletes all occurrences of the specified key.sort(): Sorts all key-value pairs alphabetically by key.
const params = new URLSearchParams();
// Append values
params.append('tag', 'js');
params.append('tag', 'react');
// Set a single unique key
params.set('page', '1');
// Overwrite an existing key
params.set('page', '2');
// Remove a parameter
params.delete('tag');Serializing to a Query
String: toString()
To convert a URLSearchParams object back into a valid
URL-encoded query string, call toString(). Characters that
require encoding (like spaces, ampersands, or special symbols) are
encoded automatically according to application/x-www-form-urlencoded
rules.
const params = new URLSearchParams();
params.set('search', 'web development');
params.set('filter', 'price > 100');
console.log(params.toString());
// Output: "search=web+development&filter=price+%3E+100"When used alongside the URL object, updating
url.searchParams automatically synchronizes with the
url.search property:
const url = new URL('https://example.com/search');
url.searchParams.set('q', 'modern javascript');
url.searchParams.set('page', '3');
console.log(url.href);
// Output: "https://example.com/search?q=modern+javascript&page=3"