378

Consider:

http://example.com/page.html?returnurl=%2Fadmin

For js within page.html, how can it retrieve GET parameters?

For the above simple example, func('returnurl') should be /admin.

But it should also work for complex query strings...

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
compile-fan
  • 15,145
  • 19
  • 53
  • 70
  • 3
    You might want to look at https://developer.mozilla.org/en/DOM/window.location for the properties of the `Location` object. – asleepysamurai Mar 27 '11 at 10:19

17 Answers17

423

With the window.location object. This code gives you GET without the question mark.

window.location.search.substr(1)

From your example it will return returnurl=%2Fadmin

EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}

I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.

Or otherwise with plain for loop, which will work even in IE8:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}
Moha the almighty camel
  • 3,876
  • 3
  • 25
  • 48
Bakudan
  • 17,636
  • 9
  • 48
  • 69
  • 2
    It should also work for complex query strings... – compile-fan Mar 27 '11 at 10:20
  • 1
    It will return all of the get query regardless of the size, but it will be one loooong string. – Bakudan Mar 27 '11 at 10:25
  • For `returnurl` it should be `/admin`... – Qwerty Jun 19 '14 at 10:45
  • 3
    This answer is completely wrong by both question definition and implementation. So if you are going to return the whole querystring anyways, which is not what the asker asked, you should use `location.search.substr(1)` at least. – Qwerty Jun 19 '14 at 10:47
  • 1
    I like it. I like the plain `for` version too. Changed my downvote. Anyway, the reason why I suggested `substr`, `substring` or `slice` `(1)` is because there is unnecessary task of reading and searching the ? in `replace()`. – Qwerty Jul 03 '14 at 09:24
  • 1
    @Qwerty I changed to substring - there might be a question mark inside the query string ( even escaped - %3F ) – Bakudan Jul 03 '14 at 09:37
  • What is your experience - is `forEach` supported in more or less all browsers used currently? Or should one better use the `for` version to be on the safe side? – Peter T. Aug 18 '16 at 10:25
  • @PediT.- it depends what are the requirements for support. If you want to use the newest features use [Babel](https://babeljs.io/) – Bakudan Aug 18 '16 at 10:29
  • @PediT. https://caniuse.com/#search=forEach – extempl Apr 10 '19 at 04:30
  • Why continue looping through all GET parameters when the searched parameter has already been found? In the for() version, I would put a return directly in the if() clause inside of the loop. => This is also why I prefer the for() loop in this case: there's no way of stopping a foreach() loop ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description ) – fpierrat Sep 06 '19 at 10:06
  • 1
    if the parameter contains "=" character this method fails. Instead you should now your parameter names and parse according to names ie: split("{}=".format($param_name))... – Emre Bayram Aug 25 '20 at 18:16
  • @EmreBayram: Good point. How about so: `let key = item.split('=', 1)[0]; let value = item.includes('=') ? item.replace(/^[^=]+=/, '') : '1';` This will set the value '1' in case of there being no '=' at all and also handle multiple '='s at the same time. – Markus-Hermann Oct 22 '20 at 07:30
  • Thanks for findGetParameter() function, it saves me – Orman Faghihi Mohaddes Apr 16 '21 at 07:10
274

window.location.search will return everything from the ? on. This code below will remove the ?, use split to separate into key/value arrays, then assign named properties to the params object:

function getSearchParameters() {
    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}

function transformToAssocArray( prmstr ) {
    var params = {};
    var prmarr = prmstr.split("&");
    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }
    return params;
}

var params = getSearchParameters();

You can then get the test parameter from http://myurl.com/?test=1 by calling params.test.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
weltraumpirat
  • 22,212
  • 5
  • 38
  • 53
  • 6
    @Bakudan `for...in` is when you are working with objects. With arrays the for loop is preferred, see [this question on `for...in` with arrays](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) – Charles Sprayberry Nov 16 '12 at 14:35
  • It doesn't hurt much, but point taken. For reasons that are explained here: http://programmers.stackexchange.com/a/120362 , though, I won't return `null`, but the empty `{}` Object. – weltraumpirat Jan 12 '14 at 13:06
  • Maybe you should make this a function and insert: if (prmstr == "") { return null; } at line 2. Otherwise if there's no '?' in the URL you end up with a 'params' set to Object {: undefined}, which is weird. – dcoz Jan 13 '14 at 11:01
  • 1
    @weltraumpirat, I was actually on my way to edit my comment to suggest returning {} instead and I didn't see your reply. In any case thanks for updating your code :) – dcoz Jan 13 '14 at 11:05
  • I have adapted your wonderful code to allow for situations like `?q=abc&g[]=1&g[]=2` to become an assoc array with 2 params: q & g where g is an Array with 2 values. https://gist.github.com/simkimsia/11372570 – Kim Stacks Apr 28 '14 at 13:46
  • heads-up to anyone reading this: some older applications separate parameters with a semicolon rather than an ampersands. – Woodrow Barlow May 11 '16 at 20:58
  • thanks ! worked perfectly for me :) – Yash Kumar Verma Jan 17 '17 at 05:36
  • `prmstr != null && prmstr != ""` is redundant. Unless you use !== for type specific comparison, you can just shorten that to `!prmstr`. – Gerald Nov 01 '17 at 14:44
151

tl;dr solution on a single line of code using vanilla JavaScript

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

This is the simplest solution. It unfortunately does not handle multi-valued keys and encoded characters.

"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin"  // Overridden with the last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined

Multi-valued keys and encoded characters?

See the original answer at How can I get query string values in JavaScript?.

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

In your example, you would access the value like this:

"?returnurl=%2Fadmin"
> qd.returnurl    // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Qwerty
  • 19,992
  • 16
  • 88
  • 107
  • 4
    Seems to be the best answer here. – Naveed Hasan Jan 29 '14 at 14:33
  • 1
    Thank you for noticing my error. I also took the liberty of modifying your code, removing the second split invocation, which can be replaced with a local variable. – Bakudan Jul 02 '14 at 15:49
  • Short and easy to understand :) – Phuong Feb 02 '16 at 02:51
  • what is vanilla? another js injected? @NaveedHasan – gumuruh Jul 26 '16 at 02:21
  • 1
    @NaveedHasan VanillaJS is a term originating from a joke name for pure javascript without additional libraries. [See here.](http://stackoverflow.com/questions/20435653/what-is-vanillajs) – Qwerty Jul 26 '16 at 10:29
  • You can add decodeURIComponent() to this: `var queryDict = {}; location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = decodeURIComponent(item.split("=")[1])}); queryDict` – Peter T. Aug 17 '16 at 12:29
121

You should use URL and URLSearchParams native functions:

let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")
let params = new URLSearchParams(url.search);
let sourceid = params.get('sourceid') // 'chrome-instant'
let q = params.get('q') // 'mdn query string'
let ie = params.has('ie') // true
params.append('ping','pong')

console.log(sourceid)
console.log(q)
console.log(ie)
console.log(params.toString())
console.log(params.get("ping"))

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://polyfill.io/v2/docs/features/

Sergiu Sandrean
  • 431
  • 5
  • 10
AKnox
  • 1,965
  • 3
  • 16
  • 19
39

A more fancy way to do it: :)

var options = window.location.search.slice(1)
                      .split('&')
                      .reduce(function _reduce (/*Object*/ a, /*String*/ b) {
                        b = b.split('=');
                        a[b[0]] = decodeURIComponent(b[1]);
                        return a;
                      }, {});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Stefan
  • 3,540
  • 4
  • 31
  • 37
12

I do it like this (to retrieve a specific get-parameter, here 'parameterName'):

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
lsblsb
  • 121
  • 1
  • 2
  • This is nice and short. I also prefer to do that in my code. – Michael Yagudaev Jan 16 '16 at 22:25
  • This is nice and works, but generates an error when the parameter is omitted... You can fix it by storing the match in a variable and checking if it equals `null`, but that ruins the one-line nature :/ – rinogo Feb 04 '16 at 23:47
12

This one uses a regular expression and returns null if the parameter doesn't exist or doesn't have any value:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ali
  • 18,627
  • 13
  • 75
  • 90
7

Here I've made this code to transform the GET parameters into an object to use them more easily.

// Get Nav URL
function getNavUrl() {
    // Get URL
    return window.location.search.replace("?", "");
};

function getParameters(url) {
    // Params obj
    var params = {};
    // To lowercase
    url = url.toLowerCase();
    // To array
    url = url.split('&');

    // Iterate over URL parameters array
    var length = url.length;
    for(var i=0; i<length; i++) {
        // Create prop
        var prop = url[i].slice(0, url[i].search('='));
        // Create Val
        var value = url[i].slice(url[i].search('=')).replace('=', '');
        // Params New Attr
        params[prop] = value;
    }
    return params;
};

// Call of getParameters
console.log(getParameters(getNavUrl()));
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Lucas Serena
  • 71
  • 1
  • 1
3
var getQueryParam = function(param) {
    var found;
    window.location.search.substr(1).split("&").forEach(function(item) {
        if (param ==  item.split("=")[0]) {
            found = item.split("=")[1];
        }
    });
    return found;
};
3

Here is another example based on Kat's and Bakudan's examples, but making it a just a bit more generic.

function getParams ()
{
    var result = {};
    var tmp = [];

    location.search
        .substr (1)
        .split ("&")
        .forEach (function (item)
        {
            tmp = item.split ("=");
            result [tmp[0]] = decodeURIComponent (tmp[1]);
        });

    return result;
}

location.getParams = getParams;

console.log (location.getParams());
console.log (location.getParams()["returnurl"]);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
E Net Arch
  • 307
  • 4
  • 12
2

If you don't mind using a library instead of rolling your own implementation, check out https://github.com/jgallen23/querystring.

thSoft
  • 19,314
  • 5
  • 82
  • 97
2

This solution handles URL decoding:

var params = function() {
    function urldecode(str) {
        return decodeURIComponent((str+'').replace(/\+/g, '%20'));
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = urldecode(tmparr[1]);
        }
        return params;
    }

    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();

Usage:

console.log('someParam GET value is', params['someParam']);
Jonah
  • 1,940
  • 5
  • 27
  • 31
2

I have created a simple JavaScript function to access GET parameters from URL.

Just include this JavaScript source and you can access get parameters. E.g.: in http://example.com/index.php?language=french, the language variable can be accessed as $_GET["language"]. Similarly, a list of all parameters will be stored in a variable $_GET_Params as an array. Both the JavaScript and HTML are provided in the following code snippet:

<!DOCTYPE html>
<html>
  <body>
    <!-- This script is required -->
    <script>
    function $_GET() {
      // Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
      var href = window.location.href;

      // Get the protocol e.g. http
      var protocol = window.location.protocol + "//";

      // Get the host name e.g. www.google.com
      var hostname = window.location.hostname;

      // Get the pathname e.g. /files/script.php
      var pathname = window.location.pathname;

      // Remove protocol part
      var queries = href.replace(protocol, '');

      // Remove host part
      queries = queries.replace(hostname, '');

      // Remove pathname part
      queries = queries.replace(pathname, '');

      // Presently, what is left in the variable queries is : ?v=1.8.7&country=india

      // Perform query functions if present
      if (queries != "" && queries != "?") {

    // Remove question mark '?'
        queries = queries.slice(1);

        // Split all the different queries
        queries = queries.split("&");

        // Get the number of queries
        var length = queries.length;

        // Declare global variables to store keys and elements
        $_GET_Params = new Array();
        $_GET = {};

        // Perform functions per query
        for (var i  = 0; i < length; i++) {

          // Get the present query
          var key = queries[i];

          // Split the query and the value
          key = key.split("=");

          // Assign value to the $_GET variable
          $_GET[key[0]] = [key[1]];

          // Assign value to the $_GET_Params variable
          $_GET_Params[i] = key[0];
        }
      }
    }

    // Execute the function
    $_GET();
    </script>
    <h1>GET Parameters</h1>
    <h2>Try to insert some get parameter and access it through JavaScript</h2>
  </body>
</html>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
1

My solution expands on @tak3r's.

It returns an empty object when there are no query parameters and supports the array notation ?a=1&a=2&a=3:

function getQueryParams () {
  function identity (e) { return e; }
  function toKeyValue (params, param) {
    var keyValue = param.split('=');
    var key = keyValue[0], value = keyValue[1];

    params[key] = params[key]?[value].concat(params[key]):value;
    return params;
  }
  return decodeURIComponent(window.location.search).
    replace(/^\?/, '').split('&').
    filter(identity).
    reduce(toKeyValue, {});
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
gtramontina
  • 1,036
  • 9
  • 10
1

To get the parameters as a JSON object:

alert(getUrlParameters().toSource())

function explode(delim, str)
{
    return str.split(delim);
}

function getUrlParameters()
{
    var out = {};
    var str = window.location.search.replace("?", "");
    var subs = explode('&', str);
    for(var i = 0; i < subs.length; ++i)
    {
        var vals = explode('=', subs[i]);
        out[vals[0]] = vals[1];
    }
    return out;
}
Randhir Rawatlal
  • 185
  • 1
  • 1
  • 12
0

If you are using AngularJS, you can use $routeParams using ngRoute module

You have to add a module to your app

angular.module('myApp', ['ngRoute'])

Now you can use service $routeParams:

.controller('AppCtrl', function($routeParams) {
  console.log($routeParams); // JSON object
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
vusan
  • 4,634
  • 4
  • 36
  • 76
0

You can use the search function available in the location object. The search function gives the parameter part of the URL. Details can be found in Location Object.

You will have to parse the resulting string for getting the variables and their values, e.g. splitting them on '='.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gaurav Saxena
  • 4,167
  • 3
  • 17
  • 17