In this post, we will cover how to access query parameters in a URL using [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
.
Query parameters are sometimes called search parameters and appear at the end of a URL:
https://site.com?param1=value1¶m2=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¶m2=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);
}
#javascript #parameters #browser