URL parameters are key-value pairs appended to a URL after ?. JavaScript provides several ways to extract these parameters and convert them into an object.
- Use URLSearchParams for a clean and reliable approach.
- split() and replace() can be used for simple parameter formats.
- for...of allows custom handling of duplicate parameters.
Approach 1: Using URLSearchParams
The URLSearchParams interface provides methods to work with query parameters. Its entries() method can be used to convert the parameters into an object.
const url = "https://example.com/?name=John&age=25&city=Delhi";
const params = new URL(url).searchParams;
const result = Object.fromEntries(params);
console.log(result);
Output
{ name: 'John', age: '25', city: 'Delhi' }
- URL extracts the URL components.
- searchParams provides access to the query parameters.
- Object.fromEntries() converts the parameter entries into an object.
Approach 2: Using split() Method
The split() method can separate the query string into individual key-value pairs. Each pair can then be converted into an object property.
const url = "https://example.com/?name=John&age=25&city=Delhi";
const query = url.split("?")[1];
const result = Object.fromEntries(
query.split("&").map(param => {
const [key, value] = param.split("=");
return [key, decodeURIComponent(value)];
})
);
console.log(result);
Output
{ name: 'John', age: '25', city: 'Delhi' }
Approach 3: Using for...of Loop
The for...of loop can iterate over URLSearchParams entries and manually add each parameter to an object.
function paramsToObject(params) {
const result = {};
const searchParams = new URLSearchParams(params);
for (const [key, value] of searchParams) {
if (Object.hasOwn(result, key)) {
if (Array.isArray(result[key])) {
result[key].push(value);
} else {
result[key] = [result[key], value];
}
} else {
result[key] = value;
}
}
return result;
}
const url = "https://example.com/?name=John&age=25&city=Delhi";
const result = paramsToObject(new URL(url).search);
console.log(result);
Output
{ name: 'John', age: '25', city: 'Delhi' }
This approach also handles duplicate parameters:
const url = "https://example.com/?tag=javascript&tag=web&tag=frontend";
console.log(paramsToObject(new URL(url).search));
Output:
{
tag: ["javascript", "web", "frontend"]
}