Get url parameters and their values using javascript

In this programming tutorial, we will learn how to get url parameters and their values using javascript. Recently, while working on a project, i needed to get parameter values from url string of the current web page. So let's have a look over how i made this happen.

Get url parameters and their values using javascript

// Read the page's GET url variables and return them as an associative array.
function getUrlParametersVals()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
Now let's have a look over how to call this getUrlParametersVals() function.

This function returns an associative array with url parameters and their values. For example, let's suppose we have the following URL

http://www.yourwebsitecom/contact.php?name=Adeel&country=Pakistan 

Calling getUrlParametersVals() function would return you the following array:
{
    "name"    : "Adeel",
    "country" : "Pakistan"
}
To get the value of first parameter you will do this
var myName = getUrlParametersVals()["name"];
To get the value of second parameter you will do the same
var myCountry = getUrlParametersVals()["country"];
So that's it. 


I hope you will find this tutorial very informative. 

I love your feedback.

0 comments: