« My sister the intern and Bill Clinton | Main | Tree Falls by White House, Misses Bush »

Javascript to parse query string variables from URL

This is helpful. Get Query String variables in JavaScript :

<script>
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  alert('Query Variable ' + variable + ' not found');
}
</script>

Now make a request to page.html?x=Hello

<script>
  alert( getQueryVariable("x") );
</script>

Technorati Tags: , ,

Comments

HomeSlice

Brilliant!
This just saved me an hour or two.
Thanks!

pyth0n

Thanks, worked perfectly also saving me a couple of hours as well. :)

Stefan

Nice work! Thanks! :) But in my case i needed some case-indifferent parsing. This is easily be added by changing "pair[0] == variable" to "pair[0].toLowerCase()== variable.toLowerCase()" ... Cheers, Stefan

jeff

This is very helpful.
How about passing multi-word strings as a variable?
Is there a simple syntax to insert spaces?

Thanks

Al

As an ardent but fledgling javascript hacker, thank you

Al

Dan

Cheers, Perfect, so much easier to use than others!

Matthias

Stefan, i personally don't recommend using multi-word variables in javascript.

you can use underscores (e.g. 'my_var') or camel-case (eg. myVar)

T

great script, glad i was able to find it. it has helped to some degree

i am running into an error with it and i'm confused as to why, perhaps you could enlighten me. first, i was running into a "XML Parsing Error: not well-formed" in FireFox on the ampersand in the split() - only to realize that it was necessary to escape the & and use &. now i'm running into a "XML Parsing Error: not well-formed" message in the for loop, which has be boggled

blogging developer

Here is a blog post describing a function to parse querystring from url usign javascript:
http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx

Tejas

good one ...
it really help us a lot ...
it almost save a day for us ..
Thanks !

k

perfect, thanks a lot!

Aaron Barker

Thanks, works like a charm. Easy to understand/modify.

ie

as usual, try it in internet explorer first. window.location.search.substring(1) does't work in ie6.

anonymouse

this can really easily be modified to work with iframe sources if you need to parse from those as well.

great resource, I'm working it into my own site with some minor tweaks.

Dhairyaguptha

Saved me Two hours at least! Thanks!

N i T ! N

thnxx...

Post a comment

Comments are moderated, and will not appear on this weblog until the author has approved them.

If you have a TypeKey or TypePad account, please Sign In.