I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code on Snipplr. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.
So as an example if we had the following url with the javascript at the bottom in place.
http://papermashup.com/index.php?id=123&page=home
All we’d need to do to get the parameters id and page are to call this:
var first = getUrlVars()["id"]; var second = getUrlVars()["page"]; alert(first); alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
So helpful! Thank you so much
I know this is very old, but still…
There is the case of multiple values where this function is not working correctly (eg: http://papermashup.com/index.php?id=123&page=home&id=234).
I changed this part:
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
if(vars[key]){
if(vars[key] instanceof Array){
vars[key].push(value);
}else{
vars[key] = [vars[key], value];
}
}else{
vars[key] = value;
}
});
There is probably a more efficient way of doing it, but the key point is that when you have multiple values you should have an array of values in the vars entry.
Quick and easy function to solve the problem.
Thanks man, exactly what l needed!
Although this was written 3,5 years ago it’s still very helpful
Thank you!
thanks
Thanks, so simply and lhelpful.
Pingback: Retreive $_GET variables in JavaScript from a URL string | Eric Holmes
Awesome exactly what I needed.
thanks
Awesome exactly what I needed.
and then for example code it like so:
var t = window.$_GET(‘admin’);
you can also try this :
window.constructor.prototype.$_GET = function(key){
//alert(this.href);
var r = {};
var url = this.location.href;
var s1 = url.split(‘?’);
var s2 = s1[1].split(‘&’);
for (var i in s2){
var s3 = s2[i].split(‘=’);
r[s3[0]] = s3[1];
}
return r[key];
};
Hello, its nice article about media print, we all know media is a great source of information.
thanks, good job..
Great Work.Thanks
Thanks men. Very helpful!!!!
Pingback: Drawing Hats on Monkeys with Mechanical Turk | Monkeyologist
thanks, good job.. keep it up
Beautiful, thank you.
caching the results FTW, Kudos.
nice post.. it work for me
thank you
Great, I just love useful little scripts like this…
its working.
thanks
Very hadny code.. Keep sharing..
Thank you. Very nice codes.
Thank you. Very nice code.
Thanks it helped me…….
Genial el código!!
Greetings from Chile
Brilliant piece of code, just what I needed. Thank you to the person who wrote the original code.
great post (^u^)
do you know how to add the possibility of not including the anchor in the function call?
example:
http://www.mysite.com/index.php?id=123#main_title
when calling
var id= getUrlVars()["id"]
alert(id);
i got
123#main_title
The getUrlVar() function from here will work properly: https://gist.github.com/1771618
excellent^^ thank you!
I love it when code just works!
This is simple and it works – thank you
Thanks….
Regards,
Laxmi Damani
The following is a slight modification of your helper method: https://gist.github.com/1771618
1. It searches only the query part of the string
2. Does not create arrays or objects
3. Quits parsing at first match
4. Returns only the value asked for
Thanks for posting ~
Shouldn’t it be alert(first) and alert(second)?
Very interesting, easy and valuable snippet.
Thanks,
This worked like magic! Thank you for sharing
Correction:
Lines 04 and 05 in first snippet must be:
alert(first);
alert(second);
Thanks
Best regards
Thanks. It helped me a lot!!
Thanks for snippet.it is very useful and easy.
Hello Friends,
I want the java script code to get all bookmarked url’s .
Thanks
Awesome Post. I actually use this technique to solve a client problem instantly over the phone. It was a real live saver. Thanks.
I enjoyed your article, it was informative and entertaining. I don’t know much about this trackback thing I’ll link to your site from my blog instead. Great stuff – I’ll keep an eye out for more.
You saved my day.
I love you ^^
you made my day
Sorry for this post since it is a year old but I have a question. I am a faily newbie and appreciate any assistance. Firstly, where do I place this code? I’m assuming I can put it into my html file within javascript brackets. I’ve done that — how do I use the variable though, since it is outside the “function”? Obviously if I just place the variables on an html page it will just display as text.
Anyone looking to read the #Anchor from a url using javascript such as index.html#welcome try this.
var urlanchor = self.document.location.hash.substring(1);
Ok, thank, great regex ![]()
here the code to integrate with jQuery
$.extend({
getUrlVars: function() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
return vars;
}
});
// var name = $.getUrlVars()['name'];
thanks for the code
function getUrlVars(url) {
var vars = {};
var url = url? url.toString().split(‘?’).pop()
: window.location.search.slice(1);
url.replace(
/([^=&]+)=([^&]*)/gi,
function(m,key,value) {
key = unescape(key);
if (key) {
value = unescape(value);
if (key in vars) {
if (vars[key] instanceof Array)
vars[key].push(value);
else
vars[key] = [vars[key], value];
} else
vars[key] = value;
}
});
return vars;
}
If a key repeats (e.g. checkboxes), only the value of the last pair will be available.
“Remember you need to include the jQuery framework.”
I think not. That’s plain, old Javascript.
Woow! and Thanks
Here is a way to do the same thing, only caching the results so the regex is only run once.
var getUrlVars = (function() {
var vars;
return function() {
if(vars !== undefined) return vars;
vars = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
})();
What about window.location.search ?
I may be missing something here, but isn’t this just plain Javascript?
Hello,
Lovely article but my question is: What’s faster using Jquery’s GET variables or using PHP’s GET variables?
Thank You
Pingback: uberVU - social comments
Here is another article that I ran across to do the same thing… code is slightly different, but end result is same.
FYI, I will be tech tweeting your blog post today
Thnx
Have you given any thoughts to jQuery Form Highlighting? I’ve been hard pressed to find good resources, and judging from this article I’m guessing you may have something valuable to say. Thanks in advance!
Designer and web developer, Co-founder and Technical Director at Harkable.com London. Previously I worked at InMobi, Spotify and MySpace. Interests include photography and making short videos. Also an avid F1 fan. I also run Mega Infographics for your daily dose of the best infographics.
Follow us on Twitter and get in-stream updates.
Subscribe to all the Papermashup tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
69 discussions around Read URL GET variables with JavaScript