Sometimes, we want to check if a query string value is present via JavaScript.
In this article, we’ll look at how to check if a query string value is present via JavaScript.
How to check if a query string value is present via JavaScript?
To check if a query string value is present via JavaScript, we can use the URLSearchParams
constructor.
For instance, we write
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const product = urlParams.get("product");
to get the query string from the current URL with window.location.search
.
Then we pass queryString
into the URLSearchParams
constructor to create the urlParams
object.
Finally, we get the value of the query parameter with key 'product'
with urlParams.get
.
Conclusion
To check if a query string value is present via JavaScript, we can use the URLSearchParams
constructor.