Tell me more ×
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
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. – Purmou Dec 13 '11 at 8:24
add comment (requires an account with 50 reputation)

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.

3 Answers

up vote 1 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;
}
share|improve this answer
add comment (requires an account with 50 reputation)

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
add comment (requires an account with 50 reputation)
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
1  
No such method in the spec. – katspaugh Dec 13 '11 at 8:37
add comment (requires an account with 50 reputation)

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