JAVASCRIPT
Parse URL Query Parameters
Learn to efficiently parse and extract all query parameters from a URL string into a JavaScript object using regex and URLSearchParams.
function getQueryParams(url) {
// For a regex-only approach to demonstrate regex specifically:
const params = {};
const regex = /[?&]([^=#&]+)=([^&#]*)/g;
let match;
while ((match = regex.exec(url))) {
params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
}
return params;
}
// Example Usage:
const urlString = "https://www.example.com/page?name=John%20Doe&age=30&city=New%20York";
console.log(getQueryParams(urlString));
// Expected: { name: 'John Doe', age: '30', city: 'New York' }
const anotherUrl = "http://test.com/?q=regex+test&id=123";
console.log(getQueryParams(anotherUrl));
// Expected: { q: 'regex test', id: '123' }
How it works: This JavaScript function `getQueryParams` extracts all key-value pairs from the query string of a given URL. It uses a regular expression `/[?&]([^=#&]+)=([^&#]*)/g` to iteratively find parameter names and their corresponding values. The `decodeURIComponent` function is then used to handle URL-encoded characters, providing a clean object of parameters. While `URLSearchParams` is typically more robust for this task, this snippet demonstrates a direct regex application for parsing.