← Back to all snippets
JAVASCRIPT

Extract All Query Parameters from URL

Learn how to use regex to efficiently extract all key-value pairs of query parameters from any given URL string in JavaScript for easy data retrieval.

function getQueryParams(url) {
    const params = {};
    // Regex to match key=value pairs in the query string
    const regex = /[?&]([^=&]+)=([^&]*)/g;
    let match;
    while ((match = regex.exec(url)) !== null) {
        const key = decodeURIComponent(match[1].replace(/\+/g, ' '));
        const value = decodeURIComponent(match[2].replace(/\+/g, ' '));
        params[key] = value;
    }
    return params;
}

const url = "https://example.com/path?name=John%20Doe&age=30&city=New+York";
const queryParams = getQueryParams(url);
console.log(queryParams);
// Expected: { name: 'John Doe', age: '30', city: 'New York' }
How it works: This JavaScript function `getQueryParams` uses a regular expression to iterate through a URL's query string and extract all key-value pairs. The `/[?&]([^=&]+)=([^&]*)/g` pattern captures key-value pairs starting with `?` or `&`, handling URL-encoded characters by decoding them. The `exec` method is used in a loop to find all matches, populating an object with the extracted parameters.

Need help integrating this into your project?

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

Hire DigitalCodeLabs