Sometimes, we want to get query string values in JavaScript.
In this article, we’ll look at how to get query string values in JavaScript.
How to get query string values in JavaScript?
To get query string values in JavaScript, we can use the URLSearchParams
constructor.
For instance, we write
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
to create the URLSearchParams
instance with the query string of the current URL.
window.location.search
has the query string.
Then we get the returned query parameters in an iterable object with urlSearchParams.entries()
.
Finally, we covert the iterable object to a plain objectg with Object.fromEntries
.
The keys of params
has the query parameter keys and the values are the query parameter values.
Conclusion
To get query string values in JavaScript, we can use the URLSearchParams
constructor.