JAVASCRIPT
Extract All Query Parameters from a URL with Regex
Dynamically parse and extract all key-value query parameters from a URL string using a JavaScript regex, useful for client-side routing or data retrieval.
function getQueryParams(url) {
const params = {};
const queryString = url.split('?')[1];
if (!queryString) {
return params;
}
const regex = /([^=&]+)=([^&]*)/g;
let match;
while ((match = regex.exec(queryString)) !== null) {
params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
}
return params;
}
// Example usage:
const url = "https://example.com/search?q=javascript+regex&page=2&sort=asc";
console.log(getQueryParams(url)); // { q: "javascript regex", page: "2", sort: "asc" }
console.log(getQueryParams("https://example.com/")); // {}
How it works: This snippet provides a JavaScript function to extract all query parameters from a given URL string. It first isolates the query string and then uses a regex `([^=&]+)=([^&]*)` with the global flag (`g`) to iteratively find all key-value pairs. `decodeURIComponent` is used to handle URL-encoded characters, returning an object of parameters.