Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

3 Answers 3

up vote 7 down vote accepted
function getJsonFromUrl() {
  var query = location.search.substr(1);
  var data = query.split("&");
  var result = {};
  for(var i=0; i<data.length; i++) {
    var item = data[i].split("=");
    result[item[0]] = item[1];
  }
  return result;
}

As ricosrealm suggests, the values should be url decoded. Additionally, today (2.5 years after this answer) you can safely use Array.forEach:

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;
}
share|improve this answer
4  
Each item should be url decoded using decodeURIComponent() –  ricosrealm Jan 17 at 0:40

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
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.