Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

Accessing Browser Query Parameters in JavaScript

August 26, 2020
javascript

In this post, we will cover how to access query parameters in a URL using URLSearchParams.

Query parameters

Query parameters are sometimes called search parameters and appear at the end of a URL:

https://site.com?param1=value1&param2=value2

In the above example, we have two parameters called param1 and param2 with values value1 and value2 respectively.

window.location.search gives us the bit of the URL from the question mark:

?param1=value1&param2=value2

We could write some string manipulation code to extract the parameter values from this string, but there is a much easier way with URLSearchParams:

const params = new URLSearchParams(
  window.location.search
);
const paramValue1 = params.get("param1"); // value1

The URLSearchParams constructor takes in the query parameters part of a URL. The object that is returned gives us useful utility methods to work with the query parameters.

The get method returns the value of the parameter name passed into it. It returns null if the parameter doesn’t exist.

params.get("param-that-does-not-exist"); // null

We can check whether a parameter exists using the has method:

params.has("param1"); // true
params.has("param-that-does-not-exist"); // false

The entries method allows us to iterate through all the parameters:

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

The forEach method may feel a little more natural though for iterating:

params.forEach((value, name) => {
  console.log(value, name);
});

We can update query parameters as well:

params.set("param2", "value2-updated");
params.toString(); // ?param1=value1&param2=value2-updated

The set method doesn’t update the URL in the browser. To do that we use history.replaceState:

window.history.replaceState(
  {},
  "",
  `${location.pathname}?${params.toString()}`
);

… or history.pushState if we want to add it to the browser history:

window.history.pushState(
  {},
  "",
  `${location.pathname}?${params.toString()}`
);

The set method can also be used to add a new parameter value:

params.set("param3", "value3");
params.toString(); // ?param1=value1&param2=value2-updated&param3=value3

The delete method can be used to remove a parameter:

params.delete("param3");
params.toString(); // ?param1=value1&param2=value2-updated

URLSearchParams works in all modern browsers but unfortunately not IE. There is a pollyfill that we can use in IE though.

Did you find this post useful?

Let me know by sharing it on Twitter.
Click here to share this post on Twitter