Categories
JavaScript Answers

How to get the URL parameters inside the HTML page with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *