4 Ways Get Query String Values from URL Parameters in JavaScript or jQuery

Sometimes we need to get values through the query string in the URL on the browser address bar. But the question is how to get them in JavaScript or jquery because we need them on the client-side.

Here I’m mentioning 4 ways for getting values from query parameters. I have also displayed uses examples. You can use either of them as per your choice and need in the client-side JS or jQuery.

Get Query String Values from URL Parameters

1. Retrieve Query String Values using URLSearchParams

This is the simplest and most recommended way to retrieve values from the query string. URLSearchParams is a built-in interface in the latest browsers with a number of methods to get and manipulate values.

const urlParams = new URLSearchParams(window.location.search);
const param_x = urlParams.get('param_x');

/*
Examples:
//Query string present in the browser address bar is 'submitted=true&msg=success'

var urlParams = new URLSearchParams(window.location.search);
var has_msg = urlParams.has('msg'); // true (boolean)
var msg = urlParams.get('msg'); //success
var submitted = urlParams.get('submitted'); // true (string)
var redirect = urlParams.get('redirect'); // NULL
*/

While this interface supports a number of decent browsers, it is not available for all, especially old ones. I suggest checking the official documentation on Mozilla and Chrome. It has various useful methods to utilize.

2. Regular Expression in JavaScript

Here is the function which will safely decode URL components using a regular expression. We can call this function and pass the query string parameter’s name as an argument to obtain the value.

<script type="text/javascript">
    function getUrlParameter(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    var qsp = 'game',
        para = getUrlParameter(qsp);
</script>

Suppose we have the URL as follows: `http://example.com/sports?game=football`.

If we wish to retrieve the value for the game query parameter, we can pass it to the qsp variable as a string and we will get football as value. If the parameter doesn’t exist then the function would simply return an empty string.

3. Simple JavaScript Function to get Query Parameters Values Object

We can also get the whole query string as an object and then access the value of a particular parameter by its key.

function get_query(){
    var url = document.location.href;
    var qs = url.substring(url.indexOf('?') + 1).split('&');
    for(var i = 0, result = {}; i < qs.length; i++){
        qs[i] = qs[i].split('=');
        result[qs[i][0]] = decodeURIComponent(qs[i][1]);
    }
    return result;
}

The function above performs the following steps:

  1. Getting the URL
  2. Parsing query string by splitting the URL
  3. Looping through each and every key in the parsed query string
  4. Storing every key and its value as an object
  5. Return the object

Below is an example:

// Query string in the URL
// x=5&y&z=hello&x=6

var result = get_query();
console.log(result);

//Output
{
  x: "6",
  y: undefined,
  z: "hello"
}

4. jQuery Way to Get Query String Values from URL Parameters

If you want a jQuery way to get a specific URL parameter’s value then here is the function.

(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

// Usage
var param = jQuery.QueryString["param"];

Hope these 4 functions will help you to get values of query string parameters in a URL. If you have any queries or any jQuery/JavaScript issue then feel free to contact us.

You Might Interested In

1 COMMENT

  1. Juan Carlos Neufeld says:

    Hi Amit!
    Very good post.
    3. Simple JavaScript Function works fine for me.
    Thank’s from Argentine.

    Reply

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.