JAVASCRIPT

Extracting a Specific Query Parameter from URL

A JavaScript regex function to easily extract the value of a named query parameter from a given URL string, useful for front-end routing.

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

// Example usage:
const currentUrl = "https://example.com/page?id=123&name=John%20Doe&ref=abc";
console.log(getQueryParam("id", currentUrl));     // "123"
console.log(getQueryParam("name", currentUrl));   // "John Doe"
console.log(getQueryParam("ref", currentUrl));    // "abc"
console.log(getQueryParam("missing", currentUrl)); // null
console.log(getQueryParam("emptyparam", "https://example.com/test?emptyparam&another=val")); // ""
How it works: This JavaScript function `getQueryParam` leverages regex to extract the value of a specific query parameter by its name from a URL. It first escapes the parameter name to prevent regex issues, then constructs a regex to match `?param=value` or `&param=value` patterns. The function correctly decodes URL-encoded values, providing a clean way to access individual parameters without manually splitting the URL string.

Need help integrating this into your project?

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

Hire DigitalCodeLabs