views:

129

answers:

2

Hi,

How to extract QueryString from the URL in javascript?

Thank You!

+7  A: 

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

Syntactic
+6  A: 

You can easily build a dictionary style collection...

function getQueryStrings() { 
  var assoc  = {};
  var decode = function (s) { decodeURIComponent(s.replace(/\+/g, " ")); };
  var queryString = location.search.substring(1); 
  var keyValues = queryString.split('&'); 

  for(var i in keyValues) { 
    var key = keyValues[i].split('='); 
    assoc[decode(key[0])] = decode(key[1]); 
  } 

  return assoc; 
} 

And use it like this...

var qs = getQueryStrings();
var myParam = qs["myParam"]; 
Josh Stodola
Thanks You, it should work! :)
James
I hope you don't mind, I edited your answer. `unescape` is deprecated and should be replaced with `decodeURIComponent`, you shouldn't decode the full search string because it will decode encoded ampersands or equals in the parameters e.g. `?test=fish%26chips`. Also, I improved it to correctly decode `+` into a space. See my answer to a similar question [here](http://stackoverflow.com/questions/901115/get-querystring-with-jquery/2880929#2880929)
Andy E
@Andy No, I don't mind at all! I agree with you. It would have handled basic query strings just fine, but now this is a more *complete* answer.
Josh Stodola
It says: `Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat`, should I care?
Tom Brito
@Tom Yes that is an error that needs to be fixed (It is @Andy E's fault :P) I've updated the answer to be correct.
Josh Stodola
+1 Thanks!.....
Tom Brito