DEV Community

Juan Cruz Martinez
Juan Cruz Martinez

Posted on • Originally published at livecodestream.dev on

Working with URL parameters in JavaScript

Live Code Stream

URL parameters are information sent to a web server along with the URL when a user accesses it. They could include a specific page or resource requested, search queries, data from forms, and more.

By sending this additional information in the URL, the server can respond with customized content particular to that request. For example, a query like “?product=shoes” might display different content than “?product=hats”.

JavaScript, the programming language for browsers and all things web, provides URLSearchParams, a rich API for us to work with URL parameters; it’s convenient and easy to use, so let’s get right into it.


What Is URLSearchParams?

The best way to retrieve URL parameters using JavaScript is using the URLSearchParams API. This API provides an interface for retrieving and manipulating query strings (URL parameters) in a simple, consistent manner across modern browsers and even for NodeJS.

One important aspect to highlight is that URLSearchParams works with strings. If you want to capture the query parameters from the browser, you can use the window.location.search property.


Getting a Single URL Parameter

The first way we can retrieve a single URL parameter using URLSearchParams is by using the get() function. This function takes in one argument, which is the key for the parameter you want to retrieve and returns its corresponding value as a string.

To illustrate this, let’s take an example with a query string:

// const queryString = window.location.search;
const queryString = '?page=5&sort=name&test=true';
const urlParams = new URLSearchParams(queryString);

urlParams.get('page'); // outputs: 5
urlParams.get('sort'); // outputs: name
urlParams.get('page_size'); // outputs: null

Enter fullscreen mode Exit fullscreen mode

Note that in our previous example, we hardcoded the values for the query string, but if you want to capture that from the browser, you can use the property window.location.search.

Additionally, you could have instances of an URL where the same key would be present more than once. In those cases, the get() function will return only the first value, but what if we want all? For that, we can use the getAll() method.

const queryString = '?page=5&sort=name&sort=age';
const urlParams = new URLSearchParams(queryString);

urlParams.get('sort'); // Outputs: 'name'
urlParams.getAll('sort'); // Outputs: ['name', 'age']

Enter fullscreen mode Exit fullscreen mode

Checking if a Query Parameter Exists

In the previous section, we noticed that when using get() on a value that is not present on the URL parameters, the result is null, and even though we could use that to check if the parameter exists, it is not the cleanest way. The URLSearchParams object contains a method for exactly this purpose: has().

Let’s see it in action:

const queryString = '?page=5&sort=name&test=true&empty=';
const urlParams = new URLSearchParams(queryString);

urlParams.has('page'); // Output: true
urlParams.has('empty'); // Output: true
urlParams.has('not_there'); // Output: false

Enter fullscreen mode Exit fullscreen mode

Iterating over All URL Parameters

In some cases, most likely for debugging or testing purposes, you might want to loop through all the URL parameters you have. For that purpose, URLSearchParams provides us with two helpful methods: keys() and entries(), though as we’ll see, there’s even a more direct way.

Let’s jump into the code:

const queryString = '?page=5&sort=name&sort=age&test=true';
const urlParams = new URLSearchParams(queryString);

for (const [key, value] of urlParams) {
  console.log(key, value);
}

// Output:
// page 5
// sort name
// sort age
// test true

Enter fullscreen mode Exit fullscreen mode

Alternatively, to get an iterator we can use entries(), which for this scenario will produce the exact same behavior as before:

for (const [key, value] of urlParams.entries()) {
  console.log(key, value);
}

Enter fullscreen mode Exit fullscreen mode

Lastly, if we only need the query string parameters keys, we can use the keys() method.

const queryString = '?page=5&sort=name&sort=age&test=true';
urlParams = new URLSearchParams(queryString);

for (const key of urlParams.keys()) {
  console.log(key);
}

// Output:
// page
// sort
// sort
// test

Enter fullscreen mode Exit fullscreen mode

Lastly, if we only need all the values, we can use .values(), like with any other iterator object in JavaScript.


Bonus: Manipulating Query String Parameters

Besides just retrieving, we can also add, update and delete URL parameters.

Appending query parameters

Adding a new query parameter is done through the append() method, which takes in two arguments: the first one is the key, and the second one is its associated value.

const queryString = '?page=5';
const urlParams = new URLSearchParams(queryString);

urlParams.append('format', 'json');

console.log(urlParams.toString()); // Outputs: 'page=5&format=json'

Enter fullscreen mode Exit fullscreen mode

Updating query parameters

To change the value of a given query string parameter, you can use the method set().

const queryString = '?page=5&format=xml&sort=name&sort=age';
const urlParams = new URLSearchParams(queryString);

urlParams.set('page', '1');
urlParams.set('sort', 'gender');

console.log(urlParams.toString()); // Output: 'page=1&format=xml&sort=gender'

Enter fullscreen mode Exit fullscreen mode

Deleting query parameters

In cases when you need to remove or delete a URL parameter, you can use the delete() method.

const queryString = '?page=5&format=xml';
const urlParams = new URLSearchParams(queryString);

urlParams.delete('page')

console.log(urlParams.toString()); // Outputs: 'format=xml'

Enter fullscreen mode Exit fullscreen mode

Note that when you have more than one value and you use the method set(), it will only keep the new value, discarding all the rest.


General Compatibility

In the past, developers had to code their own functions or use polyfills to have this functionality available. However, nowadays, compatibility is fantastic, and you won’t likely need anything other than URLSearchParams.

Data on support for the mdn-api__URLSearchParams feature across the major browsers

On top of that, the API is also available on NodeJS.


In Case You Missed It: How to Get the Current URL Using JavaScript?

Sometimes, you might need to get the current URL and read or manipulate the query parameters.

For that, you’d have multiple options depending on your platform, but if you are in a browser, you can simply access the current URL’s query string by doing the following:

const queryString = window.location.search;

Enter fullscreen mode Exit fullscreen mode

On NodeJS, capturing the query parameters will depend on the framework, though most frameworks would parse this information automatically for you.

Thanks for reading!

Subscribe to my weekly newsletter for developers and builders and get a weekly email with relevant content.

Top comments (0)