← Back to all snippets
JAVASCRIPT

Parsing Query Parameters from a URL String

Extract individual query parameters and their values from a URL string using a regex pattern, ideal for client-side routing or data extraction.

function parseQueryParams(url) {
  const params = {};
  const regex = /[?&]([^=&]+)=([^&]*)/g;
  let match;
  while ((match = regex.exec(url)) !== null) {
    params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
  }
  return params;
}

const url = "https://example.com/search?q=regex+patterns&page=2&sort=date";
const queryParams = parseQueryParams(url);
console.log(queryParams); // { q: "regex patterns", page: "2", sort: "date" }
How it works: This JavaScript function uses a regex `/[?&]([^=&]+)=([^&]*)/g` to iteratively find all key-value pairs in the query string. `match[1]` captures the key, and `match[2]` captures the value. `decodeURIComponent` is used to properly handle URL-encoded characters. The `while` loop with `regex.exec()` is crucial for finding all non-overlapping matches.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs