JAVASCRIPT

Extracting URL Query Parameters with Regex

Learn to parse and extract individual query parameters and their values from a URL string in JavaScript using a regular expression, ideal for client-side routing and data handling.

function getQueryParams(url) {
  const queryParams = {};
  // Regex to match key=value pairs in the query string part of a URL
  const regex = /[?&]([^=&]+)=([^&]*)/g;
  let match;

  // Use URL object for robust parsing of the query string first
  const urlObj = new URL(url);
  const queryString = urlObj.search;

  while ((match = regex.exec(queryString)) !== null) {
    const key = decodeURIComponent(match[1]);
    const value = decodeURIComponent(match[2]);
    queryParams[key] = value;
  }
  return queryParams;
}

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

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

const url3 = "https://example.com";
console.log(getQueryParams(url3)); // {} (empty object)
How it works: This function `getQueryParams` extracts all key-value pairs from a URL's query string using a regular expression. It first uses the native `URL` object to reliably get the `search` part (query string). Then, the regex `/[?&]([^=&]+)=([^&]*)/g` iteratively finds parameters. `decodeURIComponent` is applied to both keys and values to handle URL-encoded characters correctly. This method provides a flexible way to parse query parameters, making them accessible as properties of an object.

Need help integrating this into your project?

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

Hire DigitalCodeLabs