[javascript] How to get "GET" request parameters in JavaScript?

How to get "GET" variables from request in JavaScript?

Does jQuery or YUI! have this feature built-in?

This question is related to javascript

The answer is


Just to put my two cents in, if you wanted an object containing all the requests

function getRequests() {
    var s1 = location.search.substring(1, location.search.length).split('&'),
        r = {}, s2, i;
    for (i = 0; i < s1.length; i += 1) {
        s2 = s1[i].split('=');
        r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
    }
    return r;
};

var QueryString = getRequests();

//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3

Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.

function Request(name){
    return QueryString[name.toLowerCase()];
}

You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.


You could use jquery.url I did like this:

var xyz = jQuery.url.param("param_in_url");

Check the source code

Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser


The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.

function getUrlParameter(name) {
    var urlOld          = window.location.href.split('?');
    urlOld[1]           = urlOld[1] || '';
    var urlBase         = urlOld[0];
    var urlQuery        = urlOld[1].split('#');
    urlQuery[1]         = urlQuery[1] || '';
    var parametersString = urlQuery[0].split('&');
    if (parametersString.length === 1 && parametersString[0] === '') {
        parametersString = [];
    }
    // console.log(parametersString);
    var anchor          = urlQuery[1] || '';

    var urlParameters = {};
    jQuery.each(parametersString, function (idx, parameterString) {
        paramName   = parameterString.split('=')[0];
        paramValue  = parameterString.split('=')[1];
        urlParameters[paramName] = paramValue;
    });
    return urlParameters[name];
}

Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:

var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)

Works for me in

url: http://localhost:8080/#/?access_token=111

function get(name){
  const parts = window.location.href.split('?');
  if (parts.length > 1) {
    name = encodeURIComponent(name);
    const params = parts[1].split('&');
    const found = params.filter(el => (el.split('=')[0] === name) && el);
    if (found.length) return decodeURIComponent(found[0].split('=')[1]);
  }
}

Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.

With an example:

// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else

var _GET = (function() {
    var _get = {};
    var re = /[?&]([^=&]+)(=?)([^&]*)/g;
    while (m = re.exec(location.search))
        _get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
    return _get;
})();

console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123

A map-reduce solution:

var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
        return paramPair.split(/=(.+)?/).slice(0, 2);
    }).reduce(function (obj, pairArray) {            
        obj[pairArray[0]] = pairArray[1];
        return obj;
    }, {});

Usage:

For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test
    var url = new URL(url_string);
    var paramValue = url.searchParams.get("filename");
    alert(paramValue)

You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.


If you already use jquery there is a jquery plugin that handles this:

http://plugins.jquery.com/project/query-object