86

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

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

Tiago
  • 3,113
  • 2
  • 31
  • 45
Daniel Silveira
  • 41,125
  • 36
  • 100
  • 121

12 Answers12

193

Update June 2021:

Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).

Original:

All data is available under

window.location.search

you have to parse the string, eg.

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

just call the function with GET variable name as parameter, eg.

get('foo');

this function will return the variables value or undefined if variable has no value or doesn't exist

Rafael
  • 18,349
  • 5
  • 58
  • 67
  • @Daniel Silveira: yes, it could/should decode the value (and encode the name). Will edit my post in few moments – Rafael May 06 '09 at 18:43
  • 2
    Note that decodeURIComponent does not decode /all/ possible URI escapes. In particular "+" won't be decoded as " ". (I forget which browser this was in. FF, maybe?) The spec requires them to only decode exactly what encodeUIRComponent encodes, and it will encode " " as "%20", so "+" is left alone. – Jesse Rusak May 06 '09 at 20:32
  • This is why I like PHP – ymakux May 17 '14 at 11:07
  • 2
    @volocuga unlike PHP, dealing with URLs in JavaScript is quite rare operation, so browser vendors never really focused on these features. – Rafael Jul 18 '14 at 20:15
  • brilliantly answered Rafael ;) – Jalal Sordo Feb 29 '16 at 22:04
  • @andrewdotn yes, I totally agree. I've added info about outdated solution and linked the URLSearchParams. – Rafael Jun 04 '21 at 20:29
35

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

Kaos
  • 754
  • 1
  • 8
  • 13
  • 1
    Great answer, but your link is dead – Adam Casey Feb 19 '13 at 16:09
  • @Adam it would appear so. I think this is the updated URL: https://github.com/allmarkedup/jQuery-URL-Parser A google search on Mark Perkins jquery.url led me to an update. I have the source from when I posted this answer if you need it. – Kaos Feb 25 '13 at 18:12
  • 3
    So a plugin is required? – JohnK Sep 16 '14 at 21:06
  • 1
    `var xyz = jQuery.url().param("param_in_url");` is the correct syntax where `jQuery.url()` gives the the current page URL. Please make the correction. – Ahmed Akhtar Sep 15 '17 at 17:52
21

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)
VISHNU
  • 948
  • 8
  • 15
  • not works in example http://localhost:8080/#/?access_token=111 because of location.hash part. If '#' symbol occurs location.search is empty – Maksim Tikhonov Dec 22 '18 at 13:56
  • url with "#" symbol is not supported so we have to remove that. try this : var url_string = window.location.href; // www.test.com?filename=test var url = new URL(url_string.replace("#/","")); var paramValue = url.searchParams.get("access_token"); alert(paramValue) – VISHNU Dec 24 '18 at 10:45
  • NOT supported in Internet Explorer – Sebastian Scholle Sep 18 '20 at 10:50
12

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()];
}
Kirby
  • 15,127
  • 10
  • 89
  • 104
FabianCook
  • 20,269
  • 16
  • 67
  • 115
7

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)
Nicolas Bouvrette
  • 4,295
  • 1
  • 39
  • 53
Grindlay
  • 571
  • 5
  • 8
5

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.

Dan Lew
  • 85,990
  • 32
  • 182
  • 176
3

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
Lavi Avigdor
  • 4,092
  • 3
  • 25
  • 28
  • 1
    Could you please address why would you use a map-reduce solution for this? As far as I understand, map-reduce is efficient when handling really big datasets. As this is just an HTTP request, I don't see the point of using a map-reduce solution. – JorgeGRC Sep 22 '15 at 07:56
  • 1
    actually `map/reduce` is just a collections processing mechanism: can be used with any size data. it is more famous for big data due to its willingness to be parallelized – WestCoastProjects Jan 29 '20 at 09:51
2

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
Community
  • 1
  • 1
Matt
  • 1,377
  • 2
  • 13
  • 26
1

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

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
1

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

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

brendan
  • 29,308
  • 20
  • 68
  • 109
0

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];
}
Tobi G.
  • 1,530
  • 2
  • 13
  • 16
0

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]);
  }
}
Maksim Tikhonov
  • 770
  • 6
  • 15