112

Possible Duplicate:
Use the get paramater of the url in javascript
How can I get query string values in JavaScript?

In Javascript, how can I get the parameters of a URL string (not the current URL)?

like:

www.domain.com/?v=123&p=hello

Can I get "v" and "p" in a JSON object?

6

2 Answers 2

163

2.5 years after the question was asked you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getSearchOrHashBased(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return "";
  if(hash==-1) hash = url.length;
  return question==-1 || hash==question+1
    ? url.substring(hash)
    : url.substring(question+1, hash);
}

// use query = getSearchOrHashBased(location.href)
// or query = location.search.substring(1)
function getJsonFromUrl(query) {
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.replaceAll("+", " ");
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substring(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substring(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

7 years after the question was asked the functionality was standardized as URLSearchParams and 4 more years after, the access can be further simplified by Proxy as explained in this answer, however that new one can not parse the sample url above.

15
  • 7
    Each item should be url decoded using decodeURIComponent()
    – ricosrealm
    Commented Jan 17, 2014 at 0:40
  • location.search doesn't work on hash based routing: http://localhost:9000/#/documents?lang=es will return an empty string for location.search. You would have to use location.hash or location.href instead.
    – cmfolio
    Commented Sep 30, 2014 at 16:58
  • 2
    Both the parameter name and value must be decoded. This is a common mistake. So rather than result[item[0]] = decodeURIComponent(item[1]); it should be: result[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
    – AndrewF
    Commented Oct 2, 2015 at 17:49
  • 1
    Note also that using split("=") will fail for param values that contain an unencoded =, which is uncommon but certainly does happen. I would suggest using a regular expression so that you get better logic while keeping succinctness.
    – AndrewF
    Commented Oct 2, 2015 at 18:08
  • 1
    @GuillermoMoscoso Then you would get strings like genre=R&B&name=John which could not be parsed correctly. You need to decode after you split the string and know what is key and what is value, square brackets as "key in keys" need special care here, see the code.
    – Jan Turoň
    Commented Jan 20, 2016 at 15:48
35

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

3
  • why not use window.location.getParameter?
    – codeAnand
    Commented Dec 13, 2011 at 8:28
  • Your example does not return an object (it returns 2 strings), and it requires you to know the names of the parameters beforehand, which given what the OP is trying to do, is unlikely to be the case. Also, where is the documentation for getParameter? Commented Dec 13, 2011 at 8:33
  • 5
    The param name is technically [^=#&]+ rather than just [^=#]+ -- having a name without a value is legal and common. Also make sure that both the name and value are decoded: params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
    – AndrewF
    Commented Oct 2, 2015 at 17:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.