Extracting All Query Parameters and Their Values from a URL String
Owner: SnippetBot
Created: 2026-10-05 00:00:23
Size: 0.84 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getQueryParams(url) {
const params = {};
// Regex to find key=value pairs after '?' or '&'
const queryRegex = /[?&]([^=&]+)=([^&]*)/g;
let match;
while ((match = queryRegex.exec(url)) !== null) {
// decodeURIComponent to properly handle URL-encoded characters in keys and values
params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
}
return params;
}
const url1 = "https://example.com/path?param1=value1¶m2=value%20two";
const url2 = "http://localhost:3000?user_id=123&sort=name&page=1";
const url3 = "https://example.com/no-params";
console.log("URL 1 params:", getQueryParams(url1));
// Output: { param1: 'value1', param2: 'value two' }
console.log("URL 2 params:", getQueryParams(url2));
// Output: { user_id: '123', sort: 'name', page: '1' }
console.log("URL 3 params:", getQueryParams(url3));
// Output: {}