How to get url parameter in javascript
By FoxLearn 8/28/2024 7:07:56 AM 142
Using URLSearchParams
For example:
https://example.com/?product=shirt&color=blue
You can use window.location.href
to get the full URL or window.location.search
to get just the query string.
const queryString = window.location.search; console.log(queryString); // ?product=shirt&color=blue
Pass the query string to the URLSearchParams
constructor to create an instance.
const urlParams = new URLSearchParams(queryString);
Use the get
method of URLSearchParams
to retrieve the values of specific parameters.
// Get individual parameters const product = urlParams.get('product'); // 'shirt' const color = urlParams.get('color'); // 'blue' // Log the parameters console.log(product); // shirt console.log(color); // blue
Using window.location
Object
You can manually parse the query string if you need to support older browsers:
// Get the query string from the URL const queryString = window.location.search; // Remove the '?' from the start of the query string const params = queryString.substring(1).split('&'); const queryObject = {}; params.forEach(param => { const [key, value] = param.split('='); queryObject[decodeURIComponent(key)] = decodeURIComponent(value); }); // Access parameters from the queryObject const product = queryObject['product']; // 'shirt' const color = queryObject['color']; // 'blue' // Log the parameters console.log(product); // shirt console.log(color); // blue
You can use decodeURIComponent
to properly handle encoded characters in the parameter values.
Through the above example, you can see that the URLSearchParams
approach is generally preferred for its simplicity and readability, especially in modern web development.