Javascript get the query string param from url

So, you want to get the query string parameters after the question mark from an URL such as

http://example.com/?id=123456&name=amy 

The code snippet below will do. It will return you back an json object {id:’123456′,name:’amy’}

function getUrlQueryParams()
{
    var queryParams = {}, param;
    //http://example.com/?id=123456&name=amy
    //window.location.search="?id=123456&name=amy"
    var params = window.location.search.substring(1).split("&");
    for(var i = 0; i < params.length; i++)
    {
        param = params[i].split('=');
        queryParams[param[0]]=param[1];
    }
    return params;
}

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

The window.location.search stores the query string of the URL including the question mark. With the above example URL, the value of window.location.search will be “?id=123456&name=amy”. Then we use the substring function to get rid of the question mark and then split the string into an array of param pairs. At this point, each element will be a string of varaible and value pairs connected with the equal sign(=). Next, loop through the array, split each variable and value pair by the equal sign and add them to the json object.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search