Sometimes, we want to obtain the query string from the current URL with JavaScript.
In this article, we’ll look at how to obtain the query string from the current URL with JavaScript.
How to obtain the query string from the current URL with JavaScript?
To obtain the query string from the current URL with JavaScript, we can use the URL
constructor.
For instance, we write
const params = new URL(document.location).searchParams;
const name = params.get("name");
to get the current URL with document.location
to get a URL
object from the current location object.
Then we use the searchParams
property to get the query string from the current URL.
Next, we call get
with the query parameter key to return the value of the query parameter with the given key.
Conclusion
To obtain the query string from the current URL with JavaScript, we can use the URL
constructor.