AnonymousOct 16, 2023
To get query string values in JavaScript, you can use the window.location.search property to access the query string portion of the URL. Here's a step-by-step guide on how to do this:
window.location.search
const queryString = window.location.search;
2. Parse the query string into an object that contains the key-value pairs using the URLSearchParams constructor.
const urlParams = new URLSearchParams(queryString);
3. You can now access individual query parameters using the get() method or iterate through all the parameters using a loop.
Here's an example of how to retrieve a specific parameter and iterate through all parameters:
// Get a specific parameter value
const parameterValue = urlParams.get('parameterName');
console.log('Value of "parameterName":', parameterValue);
// Iterate through all parameters
urlParams.forEach((value, key) => {
console.log(`Parameter "${key}" has value: ${value}`);
});
For example, if the URL is
https://example.com/page?name=anil&age=50
the code above will allow you to access the name and age parameters and their values.