[javascript] How to retrieve GET parameters from JavaScript

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

This question is related to javascript get

The answer is


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


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"]);

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];
}

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, {});
}

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

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


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

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);

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.


You should use URL and URLSearchParams native functions:

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

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


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
}

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;
}

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;
};

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;
                      }, {});

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

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"

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:

_x000D_
_x000D_
<!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>
_x000D_
_x000D_
_x000D_