← Back to all snippets
JAVASCRIPT

Extract Specific Query Parameters from URL

A JavaScript regex function to parse URLs and extract specific query parameter values. Ideal for client-side routing, data retrieval, and manipulating URL strings.

function getQueryParam(param, url) {
  url = url || window.location.href;
  const regex = new RegExp('[?&]' + param + '(=([^&#]*)|&|#|$)');
  const results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// Example Usage:
const url = "http://example.com/page?id=123&name=John%20Doe&param3=&another=value";
console.log(getQueryParam('id', url));        // 123
console.log(getQueryParam('name', url));      // John Doe
console.log(getQueryParam('param3', url));    // ''
console.log(getQueryParam('another', url));   // value
console.log(getQueryParam('nonexistent', url)); // null

// Using current window URL
// const currentId = getQueryParam('id'); // Assumes 'id' is in window.location.href
How it works: This JavaScript function utilizes a regular expression to extract the value of a specified query parameter from a URL string. It constructs a dynamic regex to match the parameter name and capture its value. It also correctly decodes URL-encoded characters and handles cases where a parameter exists but has an empty value or is not present at all. If no URL is provided, it defaults to the current page's URL.

Need help integrating this into your project?

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

Hire DigitalCodeLabs