The URLSearchParams API in JavaScript

The URLSearchParams API provides utility methods to parse data from the query string of an URL. The URLSearchParams() constructor creates a new URLSearchParams object from the query string and returns it. It ignores the leading question mark ? in the query string, so we can pass the query string without a leading ? also.

// URL: https://myshop.com/mobiles?color=black&sort=price_asc
const search = new URLSearchParams('color=black&sort=price_asc');

The URLSearchParams() constructor can’t parse data correctly if we provide the full URL instead of the query string. If we have a full URL, we can use the URL API to parse the query string out of it and pass it to the URLSearchParams() constructor.

// Wrong way
const search = new URLSearchParams('https://myshop.com/mobiles?color=black&sort=price');

// Correct way
const url = new URL('https://myshop.com/mobiles?color=black&sort=price');
const search = new URLSearchParams(url.search);
// OR pass the query string directly 
const search = new URLSearchParams('color=black&sort=price');

Utility methods

The URLSearchParams utility methods let us easily access the query parameters and also let us add new or modify any existing parameter. Let’s explore them all.

The get() method

This method takes the query parameter name and returns the value of the first match. If no match is found, it returns null.

const search = new URLSearchParams('color=black&sort=price_asc&color=red');
console.log(search.get('color')); // 'black'
console.log(search.get('brand')); // null

The getAll() method

This method takes the query parameter name and returns all the associated values as an array. If no match is found, it returns an empty array.

const search = new URLSearchParams('color=black&sort=price_asc&color=red');
console.log(search.getAll('color')); // ['black', 'red']
console.log(search.getAll('sort')); // ['price_asc']
console.log(search.getAll('brand')); // []

The has() method

This method checks whether the provided parameter is present in the query string or not. If the parameter exists, it returns true otherwise returns false.

const search = new URLSearchParams('color=black&sort=price_asc');
console.log(search.has('sort')); // true
console.log(search.has('brand')); // false

The forEach() method

This method lets us iterate through all the query parameter values.

const search = new URLSearchParams("color=black&sort=price_asc");
search.forEach((value, key) => console.log(key, value));
// color black
// sort price_asc

The keys() method

This method returns an Iterator object containing all the query parameter names. We can either use the for…of loop to iterate over this Iterator object or convert it to an array using the spread operator or Array.from() method.

const search = new URLSearchParams("color=black&sort=price_asc");
for (const key of search.keys()) {
  console.log(key);
}
/* -output-
    color
    sort
*/

// convert to Array
console.log([...search.keys()]); // ['color', 'sort']
// OR
console.log(Array.from(search.keys())); // ['color', 'sort']

The values() method

This method returns an Iterator object containing all the query parameter values.

const search = new URLSearchParams("color=black&sort=price_asc");
console.log([...search.values()]); // ['black', 'price_asc']

The entries() method

This method returns an Iterator object containing all the key-value pairs of query parameter and their values.

const search = new URLSearchParams("color=black&sort=price_asc");
console.log([...search.entries()]); 
// [['color', 'black'], ['sort', 'price_asc']]

The append() method

This method appends a new query parameter with value to the existing query string.

const search = new URLSearchParams('color=black&sort=price_asc');
search.append('brand', 'apple');
console.log(search.toString()); 
// 'color=black&sort=price_asc&brand=apple'

The set() method

This method replaces any existing query parameter value with the provided one, and if the provided parameter doesn’t exist, it appends it. If multiple occurrences are present for the provided parameter, it removes them and replaces only the first one’s value.

const search = new URLSearchParams('color=black&sort=price_asc&color=red');
search.set('sort', 'popularity');
search.set('color', 'green');
search.set('brand', 'apple');
console.log(search.toString()); 
// 'color=green&sort=popularity&brand=apple'

The delete() method

This method deletes all the entries associated with the provided query parameter key.

search = new URLSearchParams('color=black&sort=price_asc&color=red');
search.delete('color');
search.delete('brand');
console.log(search.toString()); // 'sort=price_asc'

The sort() method

This method sorts the query string by the keys, and if multiple keys with the same name are present, then their relative order will be preserved.

const search = new URLSearchParams('sort=price&ram=8gb&color=red&ram=4gb');
search.sort();
console.log(search.toString());
// color=red&ram=8gb&ram=4gb&sort=price

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *