324

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?

3

5 Answers 5

603

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"];
Sign up to request clarification or add additional context in comments.

13 Comments

Note that solution doesn't unencode the parameter values ... and doesn't seem to explicitly handle # values in the url either? I'd suggest stackoverflow.com/questions/901115/… instead, like @Steve did
bad answer. doesn't handle fragments.
@Rory, yes: This: "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).
you should modify your code to use window.location.search, instead of slicing window.location.href
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. </superpickycomment>
|
185

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

8 Comments

Is this portable?
This does not return the search string from a url string. It only returns the current page's current address bar search string value.
@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 in the console and you'll see ?a=b&c=d.
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 "=".
use URLSearchParams. More detail on: 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');
|
35

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

5 Comments

You may want to remove + and decodeURIComponent on the way... And use window.location.search instead
Handy! Note that if you want to handle empty/null querystring elements, you'll want to add an 'if (i[0].length > 0)...' block...
Also, can't believe this required 5 lines of javascript to do. What year is it??
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.)
this solution does not take into account arrays in the query, e.g. filters[class]=Gym
27

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

Comments

-1

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(/(&|;|$)/))) : "";
};

1 Comment

I do not think people would associate string-object has having query string values in it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.