How To Get Query Params In Jquery

In this blog post, we will learn how to get query parameters from a URL using jQuery. Query parameters are the key-value pairs that follow the question mark (?) in a URL, and they can be used to pass additional information between pages or to filter the content displayed on a page.

Using the getUrlVars() Function

We can get the query parameters by creating a function called getUrlVars(), which will return an object containing the query parameters as properties. To create this function, follow these steps:

  1. Split the URL at the question mark (?) to get the query string.
  2. Split the query string at the ampersand (&) to get an array of key-value pairs.
  3. For each key-value pair, split it at the equals sign (=), and add it as a property to an object.
  4. Return the object containing the query parameters.

Here’s the code for the getUrlVars() function:

    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    }
    

Now, you can use this function to get the query parameters as an object:

    var queryParams = getUrlVars();
    console.log(queryParams);
    

Using jQuery

If you prefer to use jQuery, you can create a similar function by replacing the window.location.href with $(location).attr(‘href’):

    function getUrlVars() {
        var vars = {};
        var parts = $(location).attr('href').replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    }
    

Again, use this function to get the query parameters as an object:

    var queryParams = getUrlVars();
    console.log(queryParams);
    

Example

Let’s say you have the following URL:

https://example.com/?username=johndoe&age=30

By calling the getUrlVars() function, you will get an object containing the query parameters:

    {
        "username": "johndoe",
        "age": "30"
    }
    

Now, you can easily access the values of the query parameters using their keys:

    console.log(queryParams.username); // Output: "johndoe"
    console.log(queryParams.age);      // Output: "30"
    

And that’s how you can get query parameters in jQuery!