How to create an object containing the parameters of the current URL?
- Published
- Reading time
- 2 min read
- Length
- 320 words
On this page
How to create an object containing the parameters of the current URL?#
If you want to get the current URL parameters in an object format, you can use the following JavaScript code:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);This code gets the current URL search parameters using the URLSearchParams constructor and then converts them into an object using the Object.fromEntries method.
Explanation:#
The window.location.search property returns the query string part of the current URL, including the question mark (?).
The URLSearchParams constructor creates a new instance of the URLSearchParams object, which represents a collection of key-value pairs that can be accessed by name. It takes a string parameter that contains the query string.
The Object.fromEntries method creates a new object from an array of key-value pairs. It takes an iterable object (such as an array) of key-value pairs and returns a new object with properties that correspond to those entries.
Other ways to do it:#
- You can also use the
split()method to split the query string into an array of key-value pairs and then convert it into an object using a loop. - You can use a third-party library such as qs or hapijs/qs to parse and stringify query strings.
Here is an example code using the split() method:
const queryString = window.location.search;
const params = {};
if (queryString) {
queryString.split('&').forEach((pair) => {
const parts = pair.split('=');
const key = decodeURIComponent(parts[0]);
const value = decodeURIComponent(parts[1]);
params[key] = value;
});
}
console.log(params);This code first checks if there is a query string using the if statement. If the query string exists, it splits it into an array of key-value pairs using the split('&') method. Then, it loops over each pair, splits it into two parts using the split('=') method, and decodes them using the decodeURIComponent() method. Finally, it adds each key-value pair to the params object.