Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Possible Duplicate:
Use the get paramater of the url in javascript
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?

share|improve this question

marked as duplicate by Jared Farrish, Quentin, graphicdivine, derobert, Graviton Dec 14 '11 at 6:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
You can check out this post on the matter stackoverflow.com/questions/901115/… – Erik Nordenhök Dec 13 '11 at 8:19
    
Here's a nice little snippet. – Purag Dec 13 '11 at 8:24
    
check ans without regular expression stackoverflow.com/questions/19491336/get-url-parameter-jquery/… – Sameer Kazi Apr 17 '15 at 3:23
up vote 34 down vote accepted

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl() {
  var query = location.search.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 (@AndrewF)

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

function getJsonFromUrl(hashBased) {
  var query;
  if(hashBased) {
    var pos = location.href.indexOf("?");
    if(pos==-1) return [];
    query = location.href.substr(pos+1);
  } else {
    query = location.search.substr(1);
  }
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]");
      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;
}

I also replaced non-encoded + for space according to this article which is also useful guide how to encode adhering to RFC 3986.

Note the result[key][index] = val: a new array item is created, it is enumerable, so it can be iterated by forEach call. Therefore, you can parse even URLs like

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

var obj = getJsonFromUrl()["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
*/
share|improve this answer
5  
Each item should be url decoded using decodeURIComponent() – ricosrealm Jan 17 '14 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 Sep 30 '14 at 16:58
1  
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 Oct 2 '15 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 Oct 2 '15 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ň Jan 20 at 15:48

You could get a JavaScript object (a map) of 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.

share|improve this answer
    
why not use window.location.getParameter? – codeAnand Dec 13 '11 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? – James Allardice Dec 13 '11 at 8:33
    
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 Oct 2 '15 at 17:53
var v = window.location.getParameter('v');
var p = window.location.getParameter('p');

now v and p are objects which have 123 and hello in them respectively

share|improve this answer
4  
No such method in the spec. – katspaugh Dec 13 '11 at 8:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.