Sometimes, we want to get the URL parameters inside the HTML page with JavaScript.
In this article, we’ll look at how to get the URL parameters inside the HTML page with JavaScript.
How to get the URL parameters inside the HTML page with JavaScript?
To get the URL parameters inside the HTML page with JavaScript, we can use the URLSearchParams
constructor.
For instance, we write:
const params = new URLSearchParams(document.location.search);
const s = params.get("s");
const o = params.get("o");
console.log(s, o)
to create a URLSearchParams
instance with the query string of the current page URL, which we get from document.location.search
.
Next, we get the value of the s
and o
query parameters with params.get
.
Therefore, if the current page URL has the query string s=1&o=2
, then s
is 1, and o
is 2.
Conclusion
To get the URL parameters inside the HTML page with JavaScript, we can use the URLSearchParams
constructor.