The Netlobo logo - a Nevada desert landscape

Comments for Get URL Parameters Using Javascript

< Back to the article

124 comments for this article.

RSS Feed Icon Subscribe to the comments for this article

Posted: 2007-07-10 15:05:04 by Andy
What about using location.search ?
See this article for an example...

adamv.com/dev/javascript/querystring
Posted: 2007-07-10 15:15:44 by lobo235 - Netlobo Staff Member
This looks like a good way to do it too but I can see a couple disadvantages to doing it this way.

1. That code does not properly handle URLs with an anchor in them like:
http://www.test.com/i.html?b=1&c=2#34
What happens when you try to get the 'c' parameter is that it gives you 2#34 instead of just the number 2. The function I wrote handles this case properly.

2. The code you reference is also more lines of code which causes it to load slower and use more bandwidth, etc. I like to keep things short and simple.
Posted: 2007-07-12 19:05:40 by Milton
I like your code... it's useful and well thought... cheers and keep doing the good work!
Posted: 2007-09-12 16:42:15 by Serge
I was searching how to do this properly width RegExp and the pattern was not so easy for me.
Thank you very much for your code ! Very clean and clear.
Posted: 2007-09-13 13:51:42 by joe
That's exactly what I was looking for. Well Done!!
Posted: 2007-09-19 14:24:39 by Urban
The perfect solution! Witout any must-read-this-long-article-first. Beutiful! Thx.
Posted: 2007-09-27 14:25:18 by lode
Great piece of coding.

But,... i have one question.
What if the number of parameters (and their names) is unknown?

How would i solve that problem, using your code of course.

Greetz, Lode
Posted: 2007-09-27 14:53:20 by lobo235 - Netlobo Staff Member
Well, that particular problem is out of the scope of this article but you should be able to get all the parameter names using the following function which will return an Array of all parameter names. You can then lookup each parameter once you know the names.

function gpn( ) // gpn stands for 'get parameter names'
{
	var params = new Array( );
	var regex = /[\?&]([^=]+)=/g;
	while( ( results = regex.exec( window.location.href ) ) != null )
		params.push( results[1] );
	return params;
}
Posted: 2007-09-27 14:59:59 by Relic
Okay, so I was trying to use it and it's trhowing an error around the "name.replace()" it's saying its not a function. what's wrong here?
Posted: 2007-09-27 15:01:38 by lobo235 - Netlobo Staff Member
Which browser did you encounter this problem with? I have tested it with recent versions of Firefox, Opera, and IE and they all seem to work.
Posted: 2007-10-15 09:01:51 by Shubhangi
Hi,
Thanks, for your solution.
The perfect solution!!!!
This solved my most criticle problem. Only I had to copy the function and call it the way mentioned, lovely...............

Thanks..........
Posted: 2007-10-15 09:02:17 by jukimv1986
Excellent code!!!
I had been searching how to do it, and I must admit yours is the best option.
Great work! THANKS!
Posted: 2007-10-16 13:32:00 by Borewicz
Thanks for that code. Keep up wydda good work!
Posted: 2007-10-31 08:41:27 by Liam
Hi! This appears to be a good piece of work, but what I want to have it do, is when the page loads, change the location of an iFrame (id=I1) to whatever is specified in the '?url=' bit. I have no idea how to do this, as I am a VB programmer.

If you can help, I would very much appreciate it.
Posted: 2007-11-04 20:55:55 by Medina
This is a nice piece of coding.

My difficulty is that "windows.location.href" is NOT pulling the entire URL with the environment where I'm working. The parameters are getting stripped off with I capture that value.

Suggestions?
Posted: 2007-11-05 07:48:46 by Yoseph
great, take five!!!
Posted: 2007-11-14 11:26:03 by Shalini
This is awesome!! Very useful information. Saved me lots of time. Thank you :)
Posted: 2007-11-16 08:05:37 by Hallgeir
Great function :-)
It saved me an hour of work.
Thanks
Posted: 2007-12-01 22:18:52 by AllHAppy
I'm already using it ar www.AllHappyDates.com!
Thanks!
Posted: 2007-12-04 13:42:02 by Evan
Thanks a bunch. Awesome function.
Posted: 2007-12-11 14:49:05 by steve
Am I missing something? Why is the 1st line needed? I didn't think you could use [ or ] in a URL. Can someone please explain? Thanks.
Posted: 2007-12-11 15:20:39 by lobo235 - Netlobo Staff Member
There are times when the square brackets are used to represent arrays of data in a URL. For example, PHP (which is arguably the most popular programming language for the web) accepts parameters with the square brackets to denote an array of data. Here is some additional information on the subject:

http://us2.php.net/manual/en/faq.html.php#faq.html.select-multiple
Posted: 2007-12-12 12:18:47 by steve
I see. So you can use them in a URL. Such as this: example.html?test[]=1&test[]=2&test[]=val3. Thanks for clearing that up.
Posted: 2007-12-12 12:19:03 by lobo235 - Netlobo Staff Member
Yup, you got it!
Posted: 2008-01-15 10:28:21 by John
This certainly managed to answer some problems I'd been having, but does anyone know how to pass a complex url via a url? e.g. I want to pass a url in to a page via the page url to dynamically populate an iframe. The url I want to pass in is something like http://www.mytestsite.com?search=articles&avd=recent and my web site url is say http://www.mysite.com. So the full url would be http://www.mysite.com?page=http://www.mytestsite.com?search=articles&avd=recent

The problem is that the whole thing gets confused by multiple question marks etc, and it all falls over in a big heap. I end up with a 404 error in teh iframe. Is there some way please of encoding the string that's being passed, or something similar, so as to avoid this problem and get the correct url parameter back?
Posted: 2008-01-15 10:36:27 by lobo235 - Netlobo Staff Member
There should be a way to encode/escape the URL for use in another URL in pretty much any programming language. In PHP you would use urlencode( ) to encode the URL and urldecode( ) to reverse the encoding. In JavaScript you would use encodeURI( ) to encode and decodeURI( ) to decode. For more info on how to escape strings in JavaScript visit http://xkr.us/articles/javascript/encode-compare/
Posted: 2008-01-16 13:04:26 by Prema
Thanks very much for making your code available
Works like a charm!
Posted: 2008-01-22 07:07:02 by CemKalyoncu
Thanks, I needed to parse the parameters sent after the "#", I use anchor since I dont want to reload the page but when the page is reloaded manually I want it to stay the same page in the list (using ajax to show the list). Also for the url decoding you may look at
http://www.webtoolkit.info/
Posted: 2008-01-30 15:25:53 by lilroo
Great code. Do we need to credit you in the code at all if used as is?
Posted: 2008-01-30 15:27:15 by lobo235 - Netlobo Staff Member
A credit in the code (such as the url for the article) would be nice but it is not necessary. Thanks for stopping by the site!
Posted: 2008-03-01 08:49:23 by Andrew
Works a treat...BUT I'd like to see strings with "&" in them, i.e. hb.htm?n1=Andrew&n2=David, Larke & Jane&n3=John
My regex knowledge is not good enough to cope, can you help me with this?
Posted: 2008-03-07 10:36:09 by Silas
I had to re-write it cause I need the anchor variable. This will output the anchor variable.

gup = function(){
var regexS = "([\\#][^]*)";
var regex = new RegExp(regexS);
var results = regex.exec( window.location.href );
if(results == null) return "";
else return results[0].replace("#","");
}

alert(gup());
Posted: 2008-03-08 16:12:42 by raafat
excellent code....works great for me! thanks a bunch!
Posted: 2008-03-19 12:56:03 by aldo
Many tnx!! Really useful :-)
Posted: 2008-04-17 07:13:58 by sameera
very good article.. keep up wid this type of good work!! (y)
Posted: 2008-04-24 06:58:59 by Ginchen
Thanks, exactly what I was looking for! :)
Posted: 2008-05-01 13:46:07 by Derek
This is exactly what I need for a project I am working on, however I need to append the result to another script... ie

<script language="JavaScript"><!--

/* You may give each page an identifying name, server, and channel on
the next lines. */

s.pageName="Name - " + Date() + " source = " frank_param

since I'm an absolute newbie to this I'm at a loss as how to add the result to the s.pageName

Any help would be greatly appreciated.
s.server=""
s.channel=""

Posted: 2008-05-19 09:44:33 by dennyhalim
i need one that works when i call my js like this:
http://my.website/myscript.js?var1=2&var2=3

i see this function use window.location.href
so i think it wont works.

anything else i can use??
tia
Posted: 2008-05-30 07:49:32 by Jon
Great function! Does the trick for me! Thank you!
Posted: 2008-06-10 12:37:18 by Roger
Many thanks!

I was going to write the same code, but your has given me this time :-)
Posted: 2008-06-16 08:55:13 by kai
hey lobo235,
thanks for the script. I am using it for Joomla and it works well for normal URLs without SEF turned on, i.e. index.php?option=com_contact&task=view&contact_id=1&Itemid=101

however, once SEF is turned on, the URL becomes something like option,com_contact/task,view/contact_id,1/Itemid,101

The & changes to / and = changes to ,

The ? also changes to /

How do I parse the URL in this case?

Moreover, is it possible for the function to automatically detect which type of URLs are present?

Posted: 2008-06-27 09:57:23 by davgallmty
Very cool function, it helps me a lot. Thanks!
Posted: 2008-06-27 12:59:46 by bl
Hay,
This was exactly what I was looking for.

great work. Thankx mate.

bl
Posted: 2008-07-14 07:46:20 by Dielman
Possibly something easy to answer, but I'm self taught up to this point.

I've got a site that pulls an xml feed of a users Gamertag data dependent on a value in the url, that works fine. It saves that xml to a local server to later (in the page) pull the data in javascript to display it.

If I have the xmlDoc.load load a static item (eg. gamertag.xml) it works fine, but I want it to load dependent on the same url variable I use to pull the xml feed.

I've used the above to get the variable, the page recognises it (a document.write(tag_param); confirms this), but I've got no idea of how to format the xmlDoc.load to use the variable.

Feeds are saved to feeds/gamertag.xml relative to the site. Any help?

xmlDoc.load("feeds/"tag_param".xml"); was my first thoughts... But doesn't work.
Posted: 2008-07-14 07:47:54 by lobo235 - Netlobo Staff Member
Dielman,

Your idea to use the following is close:
xmlDoc.load("feeds/"tag_param".xml");

You need to change it to:
xmlDoc.load("feeds/"+tag_param+".xml");

That should do it for you.
Posted: 2008-07-21 09:11:09 by Dielman
Another follow up question.

I got the above to work, but have problems when a space or a %20 is included in the url. It isn't recognised by the script and then used.
Posted: 2008-07-24 08:36:20 by Geetanjali
This has been great help. Good job :)
Posted: 2008-08-19 09:31:23 by Dielman
Can anyone provide me with some assistance?

I've got this:

function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
name = name.replace(/\s/g,"%20");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}

var xmlDoc=null;
var tag_param = gup( 'gamertag' );

Which works, and I can verify it with

document.write(tag_param);

But for some reason when I use:

xmlDoc.load("feeds/"+tag_param+".xml");

It doesn't work, unless there's no spaces or %20's in the original URL value.

This has been driving me mad for 3 weeks, could really use some help here.
Posted: 2008-09-06 14:58:47 by rem
Hi, first of all, thanks for your get parameter names function. Works perfectly. Now to my problem:

I needed a function to get only the empty parameter names so I can replace them later with values from another array. After hours of failing at regular expressions, here is what i resorted to:


// get empty query parameters
// input string: "?action=show&a=&b=&c=&d=&e=#anker"
// return array: "a,b,c,d,e"
function getEmptyQueryParams(URL)
{

var params = new Array( );
var non_empty_params = new Array( );
var regex = /[\?&]([^=]+)=/g; // gets all query params
var regex2 = /[\?&]([a-zA-Z_]+)=[\w]/g; // gets non empty query params

while( ( results = regex.exec( URL ) ) != null )
{
params.push( results[1] );
}
while( ( results = regex2.exec( URL ) ) != null )
{
non_empty_params.push( results[1] );
}
while( non_empty_params.length > 0)
{
for(y=0;y < params.length;y++)
{
if(params[y] == non_empty_params[0])
{
params.splice(y,1);
non_empty_params.shift();
}
}
}
return params;
}



It works, but looks ugly as hell... Is there any better way to do it? Any help is appreciated.
Posted: 2008-09-08 20:30:10 by kenn
Great piece of work, bravo! (clap)
Posted: 2008-10-02 14:49:32 by ceiling-fans
Excellent. More than useful. Thank-you!
Posted: 2008-10-02 15:33:53 by KenWeiner
Great utility method. Have you thought about proposing it to be added to a common javascript library like jQuery?
Posted: 2008-10-02 15:34:40 by lobo235 - Netlobo Staff Member
KenWeiner,

I have not thought about that. Maybe I will give it a shot. Thanks for the suggestion.
Posted: 2008-10-04 09:26:39 by Feroz
That's exactly what I was looking for.
Well Done!!

You save my Time and Head... :)

Thank you very much....
Posted: 2008-10-18 22:53:03 by Balaji
Thanks a lot. Exactly what I was looking for.
Namaste!

-Balaji S.
Chennai.
Posted: 2008-10-27 09:11:04 by Yazan
Thanks for this! I was wondering: does anyone know how to make this function be case insensitive? So the url could contain, for example, sortby=0 or SortBy=0 and it would get a value of 0 in both cases by calling gup("SortBy")? Any help would be most appreciated.

thanks.
Posted: 2008-10-27 17:19:40 by Yazan
I figured out how to make it case insensitive, just pass in another parameter to the RegExp object:

var regex = new RegExp(regexS, "i");

thanks again!
Posted: 2008-11-07 13:47:00 by RikArends
Hi Guys,

I just ran into the problem of getting the URL args for a 1 page html file, and its just shocked me how many unbelievably crappy solutions are posted around the web. I hope this near 1-liner is useful to some people.
It stores all url args in a _GET object, just like PHP.

Example: http://domain/page?value=something
Access the values by alert(_GET.value);
Values are stored URI decoded and names are stored lowercase.

This all that you need:
var _GET={};
for(var m, v=location.href.split(/[?&]/), k=v.length-1;k>0;k--)
_GET[(m=v[k].split(/[=#]/))[0].toLowerCase()] = m.length>1?decodeURI(m[1]):"";
Posted: 2008-11-07 13:48:22 by RikArends
Alright, i added support for [] style PHP arrays and objects.
It autodetects if it needs to create an object or an array, depending on the type of the index. String creates an object, number creates an array.
Due to a special case in the code [-1] is treated as []. Besides, negative array indices are evil.
examples:

http : //ur/page?val[]=1&val[]=2&val[]=3;
Will be accessible as an array:
_GET.val[0] to _GET.val[2]

http : //ur/page?val[v1]=1&val.v2=2;
Will be accessible as an object:
_GET.val.v1 and _GET.val.v2

The code supports n-levels.
http : //ur/page?val[v1][0]=1;
Which will be stored as an array in
_GET.val.v1[0]

You can put quotes around names to force 'object' as type
http : //ur/page?val[v1]['1']=1;
Which will be stored properly stripped as an object:
_GET.val.v1['1']

The code is below, formatting is a bit off on this post, make it nicer if that makes you feel better :)


var _GET = {};
for(var i,a,m,n,o,v,p=location.href.split(/[?&]/),l=p.length,k=1;k<l;k++)
if( (m=p[k].match(/(.*?)(\..*?|\[.*?\])?=([^#]*)/))&&m.length==4){
n=decodeURI(m[1]).toLowerCase(),o=_GET,v=decodeURI(m[3]);
if(m[2])for(a=decodeURI(m[2]).replace(/\[\s*\]/g,"[-1]").split(/[\.\[\]]/),i=0;i<a.length;i++)
o=o[n]?o[n]:o[n]=(parseInt(a[i])==a[i])?[]:{}, n=a[i].replace(/^["\'](.*)["\']$/,"$1");
n!='-1'?o[n]=v:o[o.length]=v;
}
Posted: 2008-12-01 14:02:32 by JbL
To handle URI encoded parameters, I replaced the "else" clause with the following:

        else {
            var param = results[1];
            // decodeURIComponent doesn't recognize + as encoding for space
            param = param.replace(/\+/," ");
            param = decodeURIComponent(param); 
            return param;
        }
Posted: 2008-12-01 23:02:18 by JbL
I missed one thing in the previous post. It should be a global replace to catch all the + signs:

        else {
            var param = results[1];
            // decodeURIComponent doesn't recognize + as encoding for space
            param = param.replace(/\+/g," ");
            param = decodeURIComponent(param); 
            return param;
        }
Posted: 2008-12-10 23:43:41 by Lance
Hi,

thanks for the code, you saved me a lot of time!

do you know if it's possible to maintain the case of the url parameter? when I call the function to get the "title" parameter of this url:
http://www.mydomain.com/cmd?title=TMR%20Inventory%20-%20My%20Territory%20-%20Australia

I get the result all in lower case:
tmr inventory - my territory - australia

any ideas on how to keep the capital letters from the url?

cheers,

Lance
Posted: 2008-12-14 08:35:37 by ickla10
This code is wonderful. i looked on the web day and night for something like this. then i found this site that used it check the source and they hade the site where it came from. it works wonders for me. thanx =).
Posted: 2009-02-20 12:21:22 by Shlomo
Perfect, exactly what I was looking for
Posted: 2009-04-16 08:40:08 by Duncan
Fantastic! Exactly what I needed, so many thanks for it.
Posted: 2009-04-20 23:52:15 by AHHP
Grreat. thanks for handy function.... :)
Posted: 2009-04-29 13:22:24 by Ziliss
The function I use (it is a bit minified).
I added:
- You can pass an optional argument: an url containing parameters.
- If there is no result, return null, if there is a result but th value is missing, return "". This way I can see if a key is present without its corresponding value.
- The result is decoded, using URI decoding (idea from JbL)


function gup(name, url) { // optionally pass an URL to parse
	if (!url) url = window.location.href;
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var results = new RegExp("[\\?&]"+name+"=([^&#]*)").exec(url);
	if( results == null ) return null;
	else // decodeURIComponent doesn't recognize + as encoding for space
		return decodeURIComponent(results[1].replace(/\+/g," ")); 
}
Posted: 2009-05-01 07:53:01 by Ziliss
Why do you use:
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

Instead of one of the two following?
name = name.replace(/(\[)/,"\\\[").replace(/(\])/,"\\\]");
name = name.replace(/\[/,"\\\[").replace(/\]/,"\\\]");


They all work for me (Firefox 3).
() is the default matching expression. So maybe we should use them instead of [] ? (see http://www.regextester.com/jssyntax.html)
But it also works without them. Usually the simpler is the better. I would opt for this one.

Is there any compatibility issues that I would not be aware of ?

Thanks.
Posted: 2009-05-22 14:54:19 by Tony
Sorry I am new to JS

I am trying to modify a iFrame, I need to be able to add a param into the iFrame URL from the browser. ie: URL is www.abc123.com?utm_campaign=4499&utm_source=123

I need to capture the value to utm_campaign and place it in the iFrame URL ie:

document.write('<iFrame frameborder=0 height=1 width=1 src="https://www.test.com/test.php?hid={utm_campaign}"></iFrame>');

Please help!
Posted: 2009-05-26 07:36:52 by egeshi
Rare article. Thanks!
Posted: 2009-07-16 14:49:11 by Dan
Hello Ziliss,

Can you provide an example of how you use your gup function that contains the url to parse?

Your version looks pretty good, but I was wondering more how it was used.

Thanks.
Posted: 2009-07-16 22:00:14 by zvone
Greetings from Croatia. Thank you so much, you saved me a lot of time....
Posted: 2009-08-11 08:26:13 by Ziliss
Sorry for the late answer. Here are examples of how I use my gup function (see 6 comments above).

My gup function (with some comments):

function gup(name, url) { // optionally pass an URL to parse
	if (!url) url = window.location.href;								// if no parameter url is given, use the page URL
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");			// instruction needed if we want to extract an array
	var results = new RegExp("[\\?&]"+name+"=([^&#]*)").exec(url);
	if( results == null ) return null;									// if the name is not found, return null
	else // decodeURIComponent doesn't recognize '+' as encoding for space
		return decodeURIComponent(results[1].replace(/\+/g," ")); 
}


URL of the page the script is on: http://www.example.com/page.html?key=val

JavaScript in the page:

var exempleURL = "http://www.example.com/page2.html?color=red&size=&shape=rounded+square";

var valueOfKey = $.gup("key"); // gives: valueOfKey == "val"
var valueOfColor = $.gup("color", exempleURL); // gives: valueOfColor == "red"
var valueOfSize = $.gup("size", exempleURL); // gives: valueOfSize == ""   Thus you know the key "size" is present in the url (despite it has no value)
var valueOfShape = $.gup("shape", exempleURL); // gives: valueOfShape == "rounded square"   Decodes the '+' as a space
var valueOfPosition = $.gup("position", exempleURL); // gives: valueOfPosition == null   Thus you know the key "position" is not in the url


The exempleURL could come from any link on the page. It is usefull for ajax coding. You can intercept a click on a link and show the result on the current page :)
You can also see that if a name is found but has no result, the result is an empty string.

(Personnally in my use of this script I prefer to rename the "name" parameter to "key", as when we speak of key/value)
Posted: 2009-11-17 10:38:50 by mtranda
Thanks a bundle for this. As far as I'm concerned it does exactly what I would need it to (basically I'm using it to change the CSS class of some divs based on the parameters that are passed in the URL)


Great stuff.
Posted: 2009-12-14 12:11:44 by Tony
This helped me a lot, thanks. I have been looking for a solution to load a value into a TEXTAREA on page load for hours.
Posted: 2010-02-15 09:23:34 by kn33ch41
@RikArends: That's a handy bit of code, but in your effort to make it seem as concise (in reference to your near one-liner comment), you've obscured the code. When it's refactored, it's just as obscure. Is that your standard coding style? I'm considering building a $_GET module for JavaScript based on your code; the main difference will be that it won't pollute the global namespace.
Posted: 2010-02-23 21:43:56 by HeatherN
Thanks for this code - I think it's what I'm looking for but I need one more piece.

I have a function that shows/hides pieces of text using CSS styles and getElementById. It's working fine in the page "onclick", but I want to set it up so I can have a specific section of text open when the page loads, depending on a parameter in the URL. Each section of text (organized in <li> tags) has its id, and I'm using the id as the parameter.

How to I get my show/hide function to take the parameter from the function that extracts it from the URL?

I'm new to this and clearly getting in over my head, so any help would be greatly appreciated!
Thanks!
Posted: 2010-03-05 02:52:36 by Underhill
Thanks, this code was quite useful. I ended up using the code from Ziliss' post since it seems to handle the decoding of URI encoded parameters, etc.
Posted: 2010-03-15 22:30:37 by pres
If anyone is interested. I have created a similar function and did some <a href="http://sites.google.com/site/queryparameter/">performance improvements</a>.
Posted: 2010-04-08 08:28:48 by Tushar
Thanks!
Posted: 2010-04-11 15:40:16 by Mapper
Great snippet! Unless the function is called very frequently slower performance (due to usage of regulat expressions) is not an issue.
Posted: 2010-05-13 23:13:57 by mostwanted
thanks for the snippet!

i think it does not work, if the get-parameters are submitted via a form. tested it in IE 7 and 8 and FF 3.6.

is there a way to solve this?
Posted: 2010-05-28 07:35:14 by terzzzz
thanks a bunch for the code. It was really helpful :)
Posted: 2010-06-11 22:45:24 by cmmitw
Thanks a ton, exactly what I needed.
Posted: 2010-06-14 12:21:27 by kuvic16
At first thanks a lot of your article. I am using it to find out specific parameter\'s value from url. I got a problem. When my url like following
http://www.test.com?param1=IS20&21&param2=abcd
That means if parameter\'s value contain \'&\' then it creates a problem.
It does not pick up the actual data.
I need like that

param1=IS20&2
param2=abcd

please help me!
Posted: 2010-06-15 16:39:54 by Raul
Perfect code. Short and efficient.
Congratulations
Posted: 2010-06-19 06:02:47 by LewisCowles
why don\'t you try splitting by ? using the first array result[1] not [0] then split by # and then [0] by &, on a series of splits produces raw records which you can split by = and urldecode, you can load
Posted: 2010-06-19 06:03:18 by LewisCowles
function urldigest()
{
	var tmp = window.location.href.split("?");
	tmp = tmp[1].split("#");
	
	this.anchor = tmp[1];
	tmp = tmp[0].split("&");
		
	for(var i=0; i<tmp.length; i++)
	{
		var record = tmp[i].split("=");
		eval("this."+record[0]+" = "+\'"\'+record[1]+\'"\');
	}
	
}

var httpGET = new urldigest();
Posted: 2010-06-19 06:03:49 by bcmoney
Excellent work... can\'t tell you how much I appreciate it, but one of THE most useful pieces of JavaScript I\'ve ever come across.

This plus a little parameter validation can go a long way towards making JS play with the "grown up" server-side languages... add in HTML5 offline storage/caching, message push, capabilities http://html5demos.com/
and its yet another reason I think pretty soon we will do almost everything but heavy-lifting and distributed processing algorithm/tasks in the browser.
Posted: 2010-07-06 00:13:05 by WillDady
I need exactly this for passing url variables into Flash via SWFObject. Thanks for sharing!
Posted: 2010-07-17 00:17:53 by OrangeLobster
Just what I\'ve been looking for over a period of several weeks. Great work, thank you. Works like a charm!
Posted: 2010-07-21 13:21:43 by edup
Hi,

Im having problems passing args to flash but when using php header("Location: filename?args") function to act as a swf file. It works with firefox but not with Internet Explorer.

<object id="flashfile_obj" type="application/x-shockwave-flash" data="get_file.php?name=<?=urlencode("test.swf?&test_to_swf=1")?>" width="900" height="500">
<param name="movie" value="get_file.php?name=<?=urlencode("test.swf?&test_to_swf=1")?>"/>
<param name="quality" value="high" />
<param name="wmode" value="transparent" />
<param name="base" value="_dir" />
</object>


The file get_file.php has the code:

<?php
header("Location: ".$_REQUEST["name"]);
?>


It works on firefox but not in Internet Explorer. The flash is loaded but the argument is not passed.

Any ideas?


Thanks
Posted: 2010-08-01 11:40:52 by shaffy
Perfect code. Short and efficient.
Posted: 2010-08-25 09:00:30 by Benabdallah
Great :) i use it from now on
Posted: 2010-09-09 09:15:57 by Paul
Thanks for this nice snippet! It\'s exactly what I\'m looking.
Posted: 2010-09-14 15:48:32 by Alexander
Thank you, your post saved my time. Just corrected your code to work with URL as a parameter.
Posted: 2010-09-16 07:49:38 by Sagar
Thanks for posting this code. It helped me a lot to fetch certain URL parameters and pass the same to some other java script. Thank you once again
Posted: 2010-09-16 07:49:52 by Tannu
Thanks a lot.
This was exactly what i was looking for :)
Posted: 2010-09-22 07:13:03 by John
This doesn\'t work if there are multiple GET parameters passed with the same name. For example:

http://www.example.com?param=hi&param=world

gup("param") will return "hi" instead of an array containing both values.
Posted: 2010-09-22 07:13:17 by Mathews
Fixed but probably not the prettiest. Anyone see a bug?

function gup( name, url, retval)
{
if(!url) { url = window.location.href; }
name = name.replace(/[[]/,"\\[").replace(/[]]/,"\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null ) {
if(retval === undefined || retval.length == 0) {
return "";
} else if(retval.length == 1) {
return retval[0];
} else {
return retval;
}
} else {
if(retval === undefined || retval == null) {
retval = new Array();
retval[0] = results[1];
} else {
retval[retval.length] = results[1];
}

return gup(name, url.substring(results.index + name.length), retval);
}
}
Posted: 2010-11-17 05:17:33 by thumrith
very cool stuff and Useful to the max !!!!

cheers
Posted: 2011-01-10 07:53:09 by Jan
Works like a fairy! Thanks! :)
Posted: 2011-01-19 21:50:42 by Ershad
cool stuff.. its a gem....
Posted: 2011-01-20 09:22:52 by szabi
(window.location.href).match(/es=(.*)/)[1]

have fun :)
Posted: 2011-01-20 09:49:36 by szabi
sorry just a little clarification:

(window.location.href).match(/[?&]|variable|=(.*)/)[1]

you have to change the |variable| for the name of your variable that you\'re looking for :)

and now you can really have fun :D
Posted: 2011-02-17 05:27:22 by Thrilled2Bits
Great script and starting point to extend - well done!

Keep up the good work!
Posted: 2011-02-21 10:52:32 by Jared
There is a new library that does this called jPaq. You can build the library so that it only contains code for the jPaq.GET object. After that, if you include in page.html and go to page.html?name=jared+virnelson, you will be able to access my name through jPaq.GET["name"] or even jPaq.GET.name. Check this new library out http://jpaq.org/
Posted: 2011-03-17 22:03:45 by narayan
good code for get paremeters.
Posted: 2011-05-19 11:09:07 by James
Thank you very much, good javascript!
Posted: 2011-06-16 08:40:07 by JuanBelon
Thank you so much, i was looking for this
nice way to create the regular expression, impressive, i had use it for an embedded jscript inside a web java servlet hehe
Posted: 2011-06-23 07:23:52 by arohatech1
Thanks for sharing the information...
Posted: 2011-08-22 08:42:57 by GUXO
Great code, simple and functional.
The only thing is that I have to use Number(frank_param) to be able to use it as a number, otherwise it take it as a string
Posted: 2011-11-02 08:03:31 by ZoneMinderClient
I will be using part of this code in ZoneMinder Client v0.3.0. I am reading camera feeds from a surveillance server, getting the src property from an img element, then grabbing the monitor id from the src.

Your simplified regex example helped me. Thanks.
Posted: 2011-11-23 21:58:33 by Jorge
How would you take the result of the function gpn( ) and add it to the following JS:

GA_googleAddAttr(“KEY”, “VALUE”);

VALUE = the result of function gpn( )

Any thoughts would be appreciated.
Posted: 2011-11-26 22:05:52 by Claudio
I,

I\'m using your script, it works great... but I have a problem:
the page I need to parse has an iframe inside (for gmaps), the problem is that the script parse even the iframe page, that doesn\'t have the parameters I need.
So my result is an undefined value at the end.
I need to parse only the page that contains the iframe, not the iframe page too...
Do you have any suggestions?
Posted: 2012-02-25 10:08:56 by uyenvt
Hi, thank you. It is useful for me :)!
Posted: 2012-06-22 07:55:00 by Tim
This script was useful !
Posted: 2012-08-15 09:12:03 by AnonCode
Script works but it generates a JS error.... "name.replace is not a function".

Does anyone know how to fix this error?
Posted: 2012-08-15 09:12:14 by Annoncode
Putting the first line into a separate function seems to fix the name.replace error.

function gup(name)
{
function rplace() {
name = name.replace(/[[]/,"\\[").replace(/[]]/,"\\]");
}
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Posted: 2012-08-15 09:13:17 by Steve
Very helpful, worked better than my split. The anchor tag was getting me. Thanks!
Posted: 2012-08-15 09:14:19 by jluisgr
Very useful! Thanks!
Posted: 2012-08-15 09:17:03 by Ray
Thanks so much! It appears I was having a race condition where the browser was rendering faster than what the ASP.NET web forms control could provide.
Posted: 2012-09-12 08:57:09 by aditya
thanks a lot man i just wanted it for a simple task, thanks again you rock
Posted: 2013-01-05 09:53:55 by Jarno
Thanks, this helped me a lot.

Another question: How to remove random numbers from the end of parameter?

For example:
http://www.example.com?testid=myTest123 => returns "myTest"

RSS Feed Icon Subscribe to the comments for this article

Post your comment for the Get URL Parameters Using Javascript article:

Name (required) (letters and numbers only):
Email (required) (will not be published):
Website (include http://):
Comment (required): (HTML tags allowed: pre, strong, em, b, i)