JAVASCRIPT

Parse Query Parameters from a URL String

Use a JavaScript regex pattern to extract and parse all key-value pairs from the query string portion of a URL, useful for client-side routing.

function parseQueryParams(url) {
  const params = {};
  const queryStringMatch = url.match(/\?([^#]*)/); // Get the query string part
  if (queryStringMatch && queryStringMatch[1]) {
    const query = queryStringMatch[1];
    const paramRegex = /([^&=]+)=([^&]*)/g;
    let match;
    while ((match = paramRegex.exec(query)) !== null) {
      params[decodeURIComponent(match[1])] = decodeURIComponent(match[2].replace(/\+/g, ' '));
    }
  }
  return params;
}

// Example usage:
// const url1 = "https://example.com/page?id=123&name=Test+User";
// console.log(parseQueryParams(url1)); // { id: "123", name: "Test User" }
// const url2 = "https://example.com/home";
// console.log(parseQueryParams(url2)); // {}
How it works: This JavaScript function extracts query parameters from a given URL. First, it uses `/\?([^#]*)/` to isolate the query string (the part after '?' and before '#'). Then, it iteratively uses `/([^&=]+)=([^&]*)/g` to find all `key=value` pairs within that string. `decodeURIComponent` is used to properly handle URL-encoded characters, including replacing `+` with spaces, building an object of parameters.

Need help integrating this into your project?

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

Hire DigitalCodeLabs