Being a frontend developer, you should be aware of how to manipulate query string parameters on the client-side. Today, we'll look at the URLSearchParams interface that can be used to add, update or delete query string parameters in JavaScript.

Initializing URLSearchParams

To create a new instance of URLSearchParams, just pass the query string part of the URL (with or without the initial ?) to its constructor.

If you are working in a browser, you can access the query string part of the current URL with window.location.search:

const params = new URLSearchParams(window.location.search);

Alternatively, you can create a new URL object and retrieve all query parameters like below:

// current URL
const url = "http://example.com?size=M&color=blue&price=29&sort=desc";

// create a URL object
const urlObj = new URL(url);

// initialize URLSearchParams
const params = new URLSearchParams(urlObj.search);

The URLSearchParams constructor also accepts a JavaScript object and automatically turns it to a query string:

const obj = {
    size: 'M',
    color: 'blue',
    price: 29,
    sort: 'desc'
};

// initialize URLSearchParams from object
const params = new URLSearchParams(obj);

Accessing Parameters

To get the value of a query parameter, you can use the get() method. If the parameter doesn't exist or it is empty, you will get a null value:

params.get('price')   // 29
params.get('page')  // null

To check if a certain query parameter is present, you can use the has() method:

params.has('size')  // true
params.has('user')   // false

You should always use the has() method to check the existence of the parameter before accessing its value. It avoids a false positive when the parameter is present in the URL but has no value i.e. size=&rows=12.

Getting multiple parameters

Sometimes a URL may contain more than one value of a single parameter. Let us look at the following URL:

http://example.com?size=M&size=XL&color=blue

The above URL is 100% valid. If you parse the above URL with URLSearchParams, it will create an array of values for the size parameter.

However, if you use the get() method to access size, you will only get the first value M. To get all values of a query string parameter, you should use the getAll() method:

params.getAll('size') // [ 'M', 'XL' ]

Modifying Parameters

The set() method can be used to add a new query parameter or update the existing parameter value:

// add new param
params.set('page', 2)

// update existing param
param.set('price', 9)

Note that if the parameter contains more than values, the set() method will remove all of them and set the new value:

// URL: http://example.com?size=M&size=XL&color=blue&price=29&sort=desc

// change `size` to `L`
params.set('size', 'L');

console.log([...params.keys()]); // [ 'size', 'color', 'price', 'sort' ]
console.log([...params.values()]); // [ 'L', 'blue', '29', 'desc' ]

To avoid overriding the existing parameter values, you should use the append() method instead. As its name suggests, append() will add a new parameter if it doesn't already exist. Otherwise, it will append a new value to it.

Here is an example:

// URL: http://example.com?size=M&size=XL&color=blue&price=29&sort=desc

// append a new color
params.append('color', 'pink');

console.log([...params.entries()]);

// [ [ 'size', 'M' ],
//   [ 'size', 'XL' ],
//   [ 'color', 'blue' ],
//   [ 'price', '29' ],
//   [ 'sort', 'desc' ],
//   [ 'color', 'pink' ] ]

To delete a query string parameter from the URL, URLSearchParams provides the delete() method:

// URL: http://example.com?size=M&size=XL&color=blue&price=29&sort=desc

// remove size
params.delete('size');

console.log([...params.entries()]);

// [ [ 'color', 'blue' ], [ 'price', '29' ], [ 'sort', 'desc' ] ]

As you can see above, the delete() method removes all values of the size parameter.

Iterating through Parameters

There are multiple ways to iterate over all parameters included in the URLSearchParams object. The first way is to use the for...of loop:

for (const p of params) {
    console.log(p);
}

// [ 'size', 'M' ]
// [ 'size', 'XL' ]
// [ 'color', 'blue' ]
// [ 'price', '29' ]
// [ 'sort', 'desc' ]

URLSearchParams also supports the forEach() loop that can be used to iterate through all values contained in the object with a callback function:

params.forEach((value, key) => {
    console.log(`${key} => ${value}`);
});

// size => M
// size => XL
// color => blue
// price => 29
// sort => desc

You can also use the key(), values(), and entries() methods to get an iterator of all keys, values, or key-value pairs available in URLSearchParams.

Getting Query String

Once you are done with the modifications, you can get all parameters as a query string by using the toString() method:

// URL: http://example.com?size=M&size=XL&color=blue&price=29&sort=desc

// remove size
params.delete('size');

// add page
params.set('page', 1);

console.log(params.toString());

// color=blue&price=29&sort=desc&page=1

Notice the missing ? in front of the query string. The toString() doesn't add it. You need to manually use ? when updating the URL with the new query string.

Browser Compatibility

At the time of writing, the URLSearchParams object is supported by all major browsers except IE and Opera Mini. However, you can use a polyfill to make sure that your application continues working even in old browsers.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.