jQuery Snippet #1: URL Parameter Fetching
Monday, November 30th, 2009
I’ve decided to provide you with a new data stream. The jQuery Snippet of the Week. Enjoy.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Read a page's GET URL variables and return them as an associative array. function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } |
When executed, this function will return a beautiful string-indexed array of your hacking pleasures.
Thanks, Roshambo and jQuery HowTo!
A shame it isn't included in jQuery's core by default (as it is in prototype.js for example)
1) How is this related to jQuery? The irony is that jQuery allows you to spell it much cleaner than you have.
2)How is the argument name a “hash”?
3) How would you handle multiple arguments with the same name?
This seems like a one-off hack that has little generality and poor execution.
1) I'll throw a dollar sign in there somewhere for ya :P
2) hashmap.
3) Bad code.
Thanks but I have been using the jqURL plugin for over a year and I really prefer it.
Hmm, link?
Why not “window.location.search”?
Its as sham that most js libraries, including jQuery, don't include this.