Last updated on March 7, 2023
To get query string values from the URL you need to use the URL interface that provides properties to read and modify the URL components. In this article, we will get query string values by using URL interface’s searchParams property.
To begin with, we need to get the current web page URL which can be obtained through the document interface property. Look at the below,
console.log(document.URL);
// Output: https://example.com/?id=20&profession=doctor
Next, create an object of the URL interface and pass the absolute URL of the current web page to the constructor. As we know that document.location returns the current page URL.
let url = (new URL(document.location));
Once the object is created, we can access the searchParams property through dot notation.
let parameters = url.searchParams;
Above we accessed the searchParams property and assigned it to the new variable parameters, which can fetch all the values from the query string through the get() method. So in the above URL, we have two key-values-based parameters, to get them we need to use the get() method.
Let’s get the parameter id value from the URL. To that we need to pass the id key as a string into the get() method.
let id = parameters.get("id");
console.log(id);
// Output: 20
Similarly, to get the profession value we need to pass the key in the get() method.
let profession= parameters.get("profession");
console.log(profession);
// Output: doctor