How to get "GET" request parameters in JavaScript?

Javascript

Javascript Problem Overview


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

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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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)

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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)

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel SilveiraView Question on Stackoverflow
Solution 1 - JavascriptRafaelView Answer on Stackoverflow
Solution 2 - JavascriptKaosView Answer on Stackoverflow
Solution 3 - JavascriptVISHNUView Answer on Stackoverflow
Solution 4 - JavascriptFabianCookView Answer on Stackoverflow
Solution 5 - JavascriptDan LewView Answer on Stackoverflow
Solution 6 - JavascriptGrindlayView Answer on Stackoverflow
Solution 7 - JavascriptLavi AvigdorView Answer on Stackoverflow
Solution 8 - JavascriptMattView Answer on Stackoverflow
Solution 9 - JavascriptThomas OwensView Answer on Stackoverflow
Solution 10 - JavascriptbrendanView Answer on Stackoverflow
Solution 11 - JavascriptTobi G.View Answer on Stackoverflow
Solution 12 - JavascriptMaksim TikhonovView Answer on Stackoverflow