JAVASCRIPT
Parse URL Query String into Object
Dynamically parse URL query string parameters into a JavaScript object using a regular expression, making it easy to access URL-based data.
function parseQueryParams(url) {
const params = {};
const queryString = url.split('?')[1];
if (!queryString) {
return params;
}
// Regex to match key=value pairs, handling optional '[]' for array-like names
const paramRegex = /([^&=?]+)=([^&]*)/g;
let match;
while ((match = paramRegex.exec(queryString)) !== null) {
let key = decodeURIComponent(match[1]);
let value = decodeURIComponent(match[2]);
// Simple handling for array-like parameters (key[]) - not full robust array parsing
if (key.endsWith('[]')) {
key = key.slice(0, -2);
if (!params[key]) {
params[key] = [];
}
params[key].push(value);
} else {
params[key] = value;
}
}
return params;
}
// Examples:
// const url1 = "https://example.com/search?query=test&page=1&category=books";
// console.log(parseQueryParams(url1)); // { query: "test", page: "1", category: "books" }
// const url2 = "https://example.com?item[]=apple&item[]=orange&color=red";
// console.log(parseQueryParams(url2)); // { item: ["apple", "orange"], color: "red" }
// const url3 = "https://example.com/no-params";
// console.log(parseQueryParams(url3)); // {}
How it works: This JavaScript function `parseQueryParams` efficiently extracts key-value pairs from a URL's query string using a regular expression. The pattern `([^&=?]+)=([^&]*)` matches each `key=value` segment. It iterates through all matches, decodes URI components, and populates a JavaScript object. It also includes basic logic to handle array-like parameters (e.g., `item[]=value`), returning an easily accessible object of query parameters.