JAVASCRIPT

Extract URL Query Parameters

Extract individual key-value pairs from a URL's query string using a JavaScript regular expression and iteration for easy data access.

function getQueryParams(url) {
  const params = {};
  // Regex to match 'key=value' pairs in the query string.
  // It handles cases with or without a '?' prefix.
  const queryRegex = /[?&]([^=&]+)=([^&]*)/g;
  let match;

  // Using exec() in a loop to find all matches
  while ((match = queryRegex.exec(url)) !== null) {
    const key = decodeURIComponent(match[1]);
    const value = decodeURIComponent(match[2]);
    params[key] = value;
  }
  return params;
}

// Examples:
const url1 = "https://example.com/search?query=javascript&page=2&sort=asc";
console.log(getQueryParams(url1));
// Expected: { query: 'javascript', page: '2', sort: 'asc' }

const url2 = "http://localhost:3000/?id=123&name=John%20Doe";
console.log(getQueryParams(url2));
// Expected: { id: '123', name: 'John Doe' }

const url3 = "https://example.com";
console.log(getQueryParams(url3));
// Expected: {}
How it works: This JavaScript function `getQueryParams` extracts key-value pairs from a URL's query string using a regular expression. The regex `/[?&]([^=&]+)=([^&]*)/g` captures all segments starting with either `?` or `&`, followed by a key (non-'=' or '&' characters) and a value (any characters until the next '&' or end of string). It uses `RegExp.exec()` in a loop with the global (`g`) flag to find all matches. `decodeURIComponent` is applied to both keys and values to correctly handle URL-encoded characters, providing a clean 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