Using JavaScript URLSearchParams

Cover Image for Using JavaScript URLSearchParams

Modern JavaScript provides a convenient utility for dealing with a url's query string parameters - URLSearchParams.

Although the utility's name suggests to "search params," it is used to work with what are more commonly referred to in web development community as "query parameters" (commonly abbreviated as "query params").

Note: URLSearchParams isn't supported by Internet Explorer. Depending on your application's build process, you may still be able to use URLSearchParams. If not, reading and updating query parameters will require third-party libraries or manual manipulation.

URLSearchParams Cheatsheet

Here's a cheatsheet with a few of the commonly used URLSearchParams methods.

const params = new URLSearchParams('foo=1&bar=2&foo=3');

// Get the first matching parameter's value
params.get('foo');
// '1'

// Return an array of all values matching the passed key
params.getAll('foo');
// ['1', '3']

// Return a boolean value if the query param is found
params.has('foo');
// true

// Update or add a query param key/value, has side effects!
// Read below for additional info on proper usage
params.set('animal', 'dog');

// Append another query parameter key/value pair
params.append('foo', 'bar');

// Delete a query parameter key/value pair
params.delete('animal');

// Output the URLSearchParam object instance as a string
params.toString();
// foo=1&bar=2&foo=3&foo=bar'

// All of the below methods are covered in greater detail in this article.
// I find myself reaching for them less frequently than the above.
// However, it's still beneficial to be aware of these.
// Read more for info on how to use!
params.keys();
params.values();
params.sort();
params.entries();
params.forEach((key, value) => console.log(key, value));

Get Started: Create a URLSearchParams instance

There are a few ways to create a new URLSearchParams object instance.

  • From a complete url (eg, 'https://megafauna.dev/?foo=bar&baz=bar')
  • From a url's string query parameters (eg, 'foo=bar&baz=bar')
  • From a sequence of pairs (eg, [["foo", "1"], ["bar", "2"]])
  • From an object (eg, { foo: 1, bar: 2 })

1. From a complete URL

// First, create a new URL interface
const url = new URL('https://megafauna.dev/?foo=1&bar=2');

console.log(url.search);
// 'foo=1&bar=2'

// Then, create a new URLSearchParams instance by using `url.search`
// URLSearchParams will handle striping the leading `?` from `url.search
const urlQueryParams = new URLSearchParams(url.search);

urlQueryParams.toString();
// 'foo=1&bar=2'

2. From a url's string query parameters

If you don't have the full url, don't sweat. There are several other ways to create a new URLSearchParams instance. A string of the url's query param is a straightforward option and often readily available on server & client environments.

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.toString();
// 'foo=1&bar=2'

It's fine if the queryParamString includes a leading ? as the character is ignored,

const urlQueryParams = new URLSearchParams('?foo=1&bar=2');

urlQueryParams.toString();
// 'foo=1&bar=2'

3. From an object

I prefer this method if I don't already have the complete url or a string of the url's query parameters.

const urlQueryParams = new URLSearchParams({
  foo: 1,
  bar: 2
});

urlQueryParams.toString();
// 'foo=1&bar=2'

Using an object to create the instance often makes sense when working with query params on the sever. Plus, it's more readable than using the next option, a sequency of pairs.

4. From a sequence of pairs

Depending on the format of your data, using a sequence of pairs may be preferable to working with an object.

Use discretion when using a sequence of pairs to initialize a URLSearchParams instance -- using an object may provide a more readable approach.

const urlQueryParams = new URLSearchParams([["foo", "1"], ["bar", "2"]]);

urlQueryParams.toString();
// 'foo=1&bar=2'

URLSearchParams's methods

Now that we've created a URLSearchParams, we can use the following methods to read, write, and sort query params.


🔦 URLSearchParams.get(): find the value of a query parameter

Use URLSearchParams.get('QUERY_PARAM') to get the first matching parameter's value.

If it does not exist, null will be returned.

Note: use .getAll() if you anticipate handling multiple query parameter keys with the same name.

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.get('bar');
// 2

urlQueryParams.get('dog');
// null

🔦 URLSearchParams.getAll(): find all of the values for a given query param

URLSearchParams.getAll() is useful if you expect multiple entries for the same query parameter key.

.getAll() returns an array regardless of whether or not the key is found.

const urlQueryParams = new URLSearchParams('foo=1&bar=2&foo=3');

urlQueryParams.getAll('foo');
// ['1', '3']

🔦 URLSearchParams.has(): check whether or not the query param exists

URLSearchParams.has() returns a boolean value to indicate whether or not a matching parameter exists for the provided string argument.

This is a useful alternative to URLSearchParams.get(), as it doesn't require the return values coercion to true or false.

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.has('foo');
// true

urlQueryParams.has('dog');
// false

🔦 URLSearchParams.set(): create a new url query param

Use this when you want to add a new query parameter or update an existing.

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.set('dog', 'true');

urlQueryParams.toString();
// 'foo=1&bar=2&dog=true'

This method should be used carefully, as it deletes other matching values. If the search parameter doesn't exist, this method creates it.

const urlQueryParams = new URLSearchParams('foo=1&bar=2&foo=3');

urlQueryParams.set('foo', 5);

urlQueryParams.toString();
// 'foo=5&bar=2'

If you want to safely create a new query parameter key & value without updating or deleting existing matches, use URLSearchParams.append().


🔦 URLSearchParams.append(): use this to add a new query param key/value pair

URLSearchParams.append() is a straightfoward way to add a new query parameter key and value.

If the query param key already exists, it won't be updated or deleted.

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.append('foo', 5);

urlQueryParams.toString();
// 'foo=1&bar=2&foo=5'

🔦 URLSearchParams.delete(): delete a query param key/value pair

As the name implies, this method is useful when deleting query parameter keys and values. I find this method useful when working to prevent certain query parameters from being carried across pages within an application.

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.delete('foo');

urlQueryParams.toString();
// 'bar=2'

🔦 URLSearchParams.keys(): check the query param keys

const urlQueryParams = new URLSearchParams('foo=1&bar=2&foo=3');

[...urlQueryParams.keys()].forEach((key) => {
  console.log(key);
});

// foo
// bar
// foo

🔦 URLSearchParams.values(): see all the query param values

const urlQueryParams = new URLSearchParams('foo=1&bar=2&foo=3');

[...urlQueryParams.values()].forEach((key) => {
  console.log(key);
});

// 1
// 2
// 3

🔦 URLSearchParams.sort(): sort query params

I have not ran into a use case for URLSearchParams.sort(), but here's a basic example in case you have a good reason to alphabetize your query parameters.

const urlQueryParams = new URLSearchParams('a=2&b=1&a=1&c=3&d=4&c=5');

urlQueryParams.sort();

urlQueryParams.toString();
// 'a=2&a=1&b=1&c=3&c=5&d=4'

🔦 URLSearchParams.entries(): iterate over query parameter key/values

You'll likely find yourself reaching for the preceding URLSearchParams methods. These methods are useful in addressing the most common query parameter manipulation use cases.

If you find yourself looking for a way to your query parameters iterable, look no further than URLSearchParams.entries(). You may not find yourself employing this method frequently, but it's nice to know it is available.

Convert query parameters to an array of objects

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

[...urlQueryParams.entries()].map(([key, value]) => {
  return { [key]: value };
});

// [
//   { "foo": "1" },
//   { "bar": "2" }
// ]

Convert query parameters to an object

The following URLSearchParams example handles cases where the query parameters contain duplicate key values.

const urlQueryParams = new URLSearchParams('foo=1&bar=2&foo=5');

[...urlQueryParams.entries()].reduce((acc, [key, value]) => {
  return {
    ...acc,
    [key]: [...(acc[key] || []), value]
  };
}, {});

// {
//   "foo": [ "1", "5" ],
//   "bar": [ "2" ]
// }

Console log all of the query parameters in a url

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

for (const [key, value] of urlQueryParams.entries()) {
  console.log(`${key} => ${value}`);
}

// foo => 1
// bar => 2

🔦 URLSearchParams.forEach(): iterate over query params using a callback`

URLSearchParams.forEach()'s utility is similar to URLSearchParams.entries().

URLSearchParams.entries() is handy when creating a new object or array based on the URLSearchParams. For simpler less complex use cases, URLSearchParams.forEach() provides a useful alternative.

Here's a simple example that loops over the query params and console logs each key/value pair:

const urlQueryParams = new URLSearchParams('foo=1&bar=2&foo=5');

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

// foo => 1
// bar => 2
// foo => 5

🔦 URLSearchParams.toString(): create a new string of url query parameters

This method can be used to output the URLSearchParams as a functional query parameter string.

Many of the above examples rely on this method to demonstrate the output, so this one might already be familiar. Here's a URLSearchParams.toString() for posterity:

const urlQueryParams = new URLSearchParams('foo=1&bar=2');

urlQueryParams.toString();
// 'foo=1&bar=2'

References