320

I have the following URL:

http://www.mysite.co.uk/?location=mylocation1

I need to get the value of location from the URL into a variable and then use it in jQuery code:

var thequerystring = "getthequerystringhere"

$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

How can I grab that value using JavaScript or jQuery?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom
  • 12,776
  • 48
  • 145
  • 240

5 Answers5

598

From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

This is what you need :)

The following code will return a JavaScript Object containing the URL parameters:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

For example, if you have the URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

This code will return:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

and you can do:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • 13
    Note that solution doesn't unencode the parameter values ... and doesn't seem to explicitly handle # values in the url either? I'd suggest http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript/901144#901144 instead, like @Steve did – Rory Jun 25 '12 at 08:16
  • 3
    bad answer. doesn't handle fragments. – Morg. Nov 04 '13 at 10:33
  • 5
    @Rory, yes: This: "http://stackoverflow.com?foo=bar#topic1" will give you {"foo" : "bar#topic"}. This is why poor guy asked for a well-known library's solution, presumably, hoping to find a solution that had had some testing done on it and covered all the bases (I'm saying that's what he was HOPING to find, not that jQuery would necessarily provide it). – kghastie Nov 05 '13 at 22:19
  • 4
    you should modify your code to use window.location.search, instead of slicing window.location.href – Agi Hammerthief Feb 26 '14 at 12:09
  • 2
    Additionally, it returns an object - JavaScript does not have associative arrays. And opening curly braces *should* go on the same line as the expression in JavaScript. – danwellman May 14 '14 at 17:33
  • 2
    I also needed to convert %5B ... so i used decodeURI in this function. – Aiphee Oct 31 '14 at 15:02
  • This function fails when hashes are in the URL. – Jake Wilson Oct 12 '15 at 17:39
  • 1
    `vars []` should be `vars {}` to use it as an object instead of an array. See http://stackoverflow.com/a/4656873/3774582 for an issue I ran into when using this code as is. – Goose Feb 29 '16 at 20:40
  • This should also have a `vars[hash[0]] = decodeURIComponent(hash[1].replace(/\+/g, ' '));` because the query parameter value can be URI encoded. – CMCDragonkai Jul 22 '16 at 12:54
  • how about when its an array `x[]=1$x[]=2`? – shorif2000 Sep 22 '16 at 13:35
  • You shouldn't split on '=', it's technically okay to have a second equals sign in the value of any key/value pair. -- Only the first equals sign you encounter (per key/value pair) should be treated as a delimiter. (Also, the equals sign isn't strictly required; it's possible to have a key with no value.) – BrainSlugs83 Jan 28 '17 at 00:53
  • Just noticed that this solutions breaks if your URL doesn't contain any query parameters, so you'd need to add an edge case like that – jarodsmk Nov 20 '18 at 07:36
  • **For who prefer the php/asp syntax:** You can use it as `getUrlVars("paramName")` and in the function you should change to `function getUrlVars(paramName)` and at the end of function `return vars[paramName]`; – Ali Sheikhpour Jan 11 '20 at 09:06
182

To retrieve the entire querystring from the current URL, beginning with the ? character, you can use

location.search

https://developer.mozilla.org/en-US/docs/DOM/window.location

Example:

// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123" 

In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:

/**
 * Accepts either a URL or querystring and returns an object associating 
 * each querystring parameter to its value. 
 *
 * Returns an empty object if no querystring parameters found.
 */
function getUrlParams(urlOrQueryString) {
  if ((i = urlOrQueryString.indexOf('?')) >= 0) {
    const queryString = urlOrQueryString.substring(i+1);
    if (queryString) {
      return _mapUrlParams(queryString);
    } 
  }
  
  return {};
}

/**
 * Helper function for `getUrlParams()`
 * Builds the querystring parameter to value object map.
 *
 * @param queryString {string} - The full querystring, without the leading '?'.
 */
function _mapUrlParams(queryString) {
  return queryString    
    .split('&') 
    .map(function(keyValueString) { return keyValueString.split('=') })
    .reduce(function(urlParams, [key, value]) {
      if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
        urlParams[key] = parseInt(value);
      } else {
        urlParams[key] = decodeURI(value);
      }
      return urlParams;
    }, {});
}

You can use the above like so:

// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }

// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }

// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName')) { 
  console.log(urlParams.parameterName);
}

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
Yene Mulatu
  • 2,226
  • 1
  • 17
  • 13
  • 8
    Is this portable? – Cheezmeister Sep 19 '13 at 19:12
  • 3
    This does not return the search string from a url string. It only returns the current page's current address bar search string value. – Dwight Dec 31 '14 at 18:51
  • @Cheezmeister: `location.search` works in Chrome, Firefox and IE10+. Might work in IE9 and lower too, but I don't have one on hand. Dwight: window.location.search returns the query string. Try it on [this page](http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url?a=b&c=d#e=f) in the console and you'll see `?a=b&c=d`. – Dan Dascalescu Jun 09 '15 at 11:02
  • 2
    There's still a bit of work to do after location.search is pulled. This is the quickest way to get you halfway there, though. You'll need to drop the "?" and split on the "&", then split each result on "=". – Artif3x Dec 08 '16 at 20:50
  • 1
    use URLSearchParams. More detail on: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams For example URL has two parameters ?id=123&category=abc var urlParams = new URLSearchParams(location.search) var id = urlParams.get('id'); var cat = urlParams.get('category'); – Syed Nasir Abbas Jan 12 '19 at 19:22
  • I made an edit with portable usage example - let's see if it gets approved. Issue with URLSearchParams() is that it is not supported by IE. https://medium.com/@sudosoul/javascript-get-url-querystring-parameters-b38b1a6e2d5f – sudo soul Feb 27 '19 at 19:23
  • The line .reduce(function(urlParams, [key, value]) { returns an error in IE 10 and some select mobile browsers – ronnz Oct 07 '20 at 10:13
  • @ronnz , please check here https://caniuse.com/ if the API is supported in the browser that you are using – Yene Mulatu Oct 07 '20 at 20:51
36

An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...

  var queries = {};
  $.each(document.location.search.substr(1).split('&'),function(c,q){
    var i = q.split('=');
    queries[i[0].toString()] = i[1].toString();
  });
  console.log(queries);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James
  • 477
  • 4
  • 6
  • 2
    You may want to remove + and decodeURIComponent on the way... And use window.location.search instead – mplungjan Sep 29 '13 at 05:02
  • Handy! Note that if you want to handle empty/null querystring elements, you'll want to add an 'if (i[0].length > 0)...' block... – ericpeters0n May 05 '16 at 19:57
  • 3
    Also, can't believe this required 5 lines of javascript to do. What year is it?? – ericpeters0n May 05 '16 at 19:57
  • You shouldn't split on '=', it's technically okay to have a second equals sign in the value of any key/value pair. -- Only the first equals sign you encounter (per key/value pair) should be treated as a delimiter. (Also, the equals sign isn't strictly required; it's possible to have a key with no value.) – BrainSlugs83 Jan 28 '17 at 00:56
  • this solution does not take into account arrays in the query, e.g. filters[class]=Gym – undefinedman Jun 26 '17 at 11:06
  • this one was exactly what I needed thanks – William Howley Sep 08 '18 at 22:17
28

Have a look at this Stack Overflow answer.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

You can use the method to animate:

I.e.:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steve
  • 50,173
  • 4
  • 32
  • 41
0

We do it this way...

String.prototype.getValueByKey = function (k) {
    var p = new RegExp('\\b' + k + '\\b', 'gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 7
    I do not think people would associate string-object has having query string values in it. – Phil Oct 27 '15 at 01:04