429

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...

3

17 Answers 17

483

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;
}
16
  • 2
    It should also work for complex query strings... Mar 27, 2011 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, 2011 at 10:25
  • 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, 2014 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 3, 2014 at 9:24
  • 1
    @Qwerty I changed to substring - there might be a question mark inside the query string ( even escaped - %3F )
    – Bakudan
    Jul 3, 2014 at 9:37
283

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.

7
  • 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 Nov 16, 2012 at 14:35
  • It doesn't hurt much, but point taken. For reasons that are explained here: programmers.stackexchange.com/a/120362 , though, I won't return null, but the empty {} Object. Jan 12, 2014 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, 2014 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, 2014 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. gist.github.com/simkimsia/11372570
    – Kim Stacks
    Apr 28, 2014 at 13:46
173

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/

11
  • 9
    Unfortunately this is not compatible with IE :'( Mar 16, 2017 at 10:58
  • 10
    Add the polyfill listed below the code snippet to patch IE and turn that frown upside down.
    – AKnox
    Mar 31, 2017 at 12:57
  • 8
    @Alexey > because it should be that var params = new URLSearchParams(window.location.search.slice(1)); Mar 20, 2018 at 10:22
  • 2
    This doesn't work on iOS Safari, which is a much larger market share than IE is.
    – Xeoncross
    Oct 3, 2018 at 19:05
  • 4
    This is strongest answer without using invented functions and tons of codes Mar 27, 2020 at 2:21
160

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"
6
  • 4
    Seems to be the best answer here. Jan 29, 2014 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 2, 2014 at 15:49
  • Short and easy to understand :)
    – Phuong
    Feb 2, 2016 at 2:51
  • what is vanilla? another js injected? @NaveedHasan
    – gumuruh
    Jul 26, 2016 at 2:21
  • 1
    @NaveedHasan VanillaJS is a term originating from a joke name for pure javascript without additional libraries. See here.
    – Qwerty
    Jul 26, 2016 at 10:29
43

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;
                      }, {});
5
  • 10
    Fancy indeed, but watch out reduce is not compatible with all browsers. More info here : stackoverflow.com/questions/7094935/ie-js-reduce-on-an-object
    – fe_lix_
    Nov 27, 2012 at 10:40
  • Notably it's not supported in IE8
    – Ian Clark
    Jan 3, 2014 at 16:35
  • If there is an url as a parameter, the decodeURIComponent will mistakenly resolve it as another &key=val pairs.
    – Qwerty
    Nov 14, 2014 at 14:37
  • As Qwerty has pointed out: decodeURIComponent should be moved inside: a[b[0]] = decodeURIComponent(b[1])
    – Peter T.
    Aug 18, 2016 at 10:07
  • Thanks, I like this a lot - if IE is not dead, IE8 definitely is. Thing I would improve are handling empty parameters (without the =value part) and the same parameter multiple times (maybe use a list). And possibly it would be safer to use Object.create(null) instead of {}. Dec 20, 2022 at 20:25
20

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];
}
5
  • Yes thanks this is what i needed :)
    – taggartJ
    Aug 22, 2019 at 2:26
  • Gets the job done perfectly. Thank you!
    – Ivan
    Apr 18, 2020 at 15:19
  • Perfect code, Thank you! Jan 14, 2021 at 4:01
  • Worked perfectly and very tiny code part. Thanks.
    – mdikici
    Apr 23, 2021 at 13:18
  • wow, nice one.. Dec 16, 2021 at 9:00
13

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

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
2
  • This is nice and short. I also prefer to do that in my code. Jan 16, 2016 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 4, 2016 at 23:47
9

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()));
6

To get the parameters as a JSON object:

console.log(getUrlParameters())

function getUrlParameters() {
    var out = {};
    var str = window.location.search.replace("?", "");
    var subs = str.split(`&`).map((si)=>{var keyVal = si.split(`=`); out[keyVal[0]]=keyVal[1];});
    return out
}
1
  • 1
    It should be noted that object.toSource() only works on Firefox. Replace the first line with alert(JSON.stringify(getUrlParameters()))
    – moosearch
    May 6, 2022 at 23:10
4

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>

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"]);
1
  • There isn't an answer or comment by the user name "Kat". User names can change at any time. What does it refer to? Oct 8, 2020 at 21:31
2

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

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']);
1

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 '='.

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, {});
}
1
  • There isn't currently any answer or comment with user name "tak3r" (user names can change at any time). What does it refer to? Oct 8, 2020 at 21:13
-1

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
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.