Sometimes, we want to read GET data from a URL using JavaScript.
In this article, we’ll look at how to read GET data from a URL using JavaScript.
How to read GET data from a URL using JavaScript?
To read GET data from a URL using JavaScript, we use the URLSearchParams
constructor.
For instance, we write
const params = new URLSearchParams(location.search);
const name = params.get("name");
const names = params.getAll("name");
to create a URLSearchParams
object with the query string part of current URL.
Then we call get
with the key name to return the first value with the key.
And we call getAll
with the key name to return the all values with the key.
Conclusion
To read GET data from a URL using JavaScript, we use the URLSearchParams
constructor.