JAVASCRIPT

Extract Query Parameters from a URL String

Discover how to extract specific query parameters or all parameters from a URL string using JavaScript regex, useful for client-side routing or data retrieval.

function getQueryParam(url, param) {
  const regex = new RegExp(`[?&]${param}(=([^&#]*))?`);
  const match = url.match(regex);
  return match ? decodeURIComponent(match[2] || "") : null;
}

function getAllQueryParams(url) {
    const regex = /[?&]([^=#]+)(?:=([^&#]*))?/g;
    let params = {};
    let match;
    while ((match = regex.exec(url)) !== null) {
        params[decodeURIComponent(match[1])] = decodeURIComponent(match[2] || "");
    }
    return params;
}

// Examples
const url = "https://example.com/page?name=John%20Doe&age=30&city=";
console.log(getQueryParam(url, "name")); // "John Doe"
console.log(getQueryParam(url, "age"));  // "30"
console.log(getQueryParam(url, "city")); // ""
console.log(getQueryParam(url, "country")); // null

console.log(getAllQueryParams(url)); 
// { name: "John Doe", age: "30", city: "" }
How it works: These JavaScript functions leverage regular expressions to parse URL query parameters. The `getQueryParam` function extracts the value of a single specified parameter by constructing a dynamic regex. The `getAllQueryParams` function uses a global regex to iterate through the URL, finding all key-value pairs, decoding them, and storing them in an object. This is highly useful for accessing data passed via the URL in web applications, whether for routing, filtering, or initial state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs