JAVASCRIPT

Parse URL Query String Parameters

Extract and parse all query parameters from a URL string into a JavaScript object, simplifying access to data passed via the URL for client-side logic.

function parseQueryParams(url) {
  const queryString = url.split('?')[1];
  if (!queryString) return {};

  const params = {};
  queryString.replace(/([^=&]+)=([^&]*)/g, function(match, key, value) {
    params[decodeURIComponent(key)] = decodeURIComponent(value);
  });
  return params;
}

// Examples
console.log(parseQueryParams('http://example.com?name=John%20Doe&age=30&city=New%20York'));
// { name: 'John Doe', age: '30', city: 'New York' }
console.log(parseQueryParams('http://example.com')); // {}
How it works: This JavaScript function `parseQueryParams` takes a URL string and extracts its query parameters into a plain JavaScript object. It splits the URL to isolate the query string, then uses a regular expression with the `replace` method's callback to iterate over each key-value pair, decoding and storing them in the `params` object. This is highly useful for client-side routing or data retrieval from URLs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs