Just a useful little javascript function which will get a URL parameter and return it to you. For example if the current URL is “…?opendocument&id=testid” then calling getURLParam(“id”) will return “testid”.
function getURLParam(strParamName){
var strReturn = “”;
var strHref = window.location.href;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)).toLowerCase();
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + “=”) > -1 ){
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
break;
}
}
}
return unescape(strReturn);
}
Update (31st December 2006)
This posting has been around for a long time now and gets a lot of traffic. Although it will still work fine as long as you know its limitations, several people have pointed to this article as being a better solution. I totally agree, it’s well worth a look.
Update (27th February 2007)
A couple of bug fixes raised via email. Thanks to Oliver Bryant for those.
if ( strHref.indexOf(“&”) > -1 ) SHOULD BE
if ( strHref.indexOf(“?”) > -1 )
strHref.substr(strHref.indexOf(“&”)) OF THE FOLLOWING LINE SHOULD BE
strHref.substr(strHref.indexOf(“?”))
SO the param string will start searching for params and valus with the first parameter always following a ? character and split subsequent pairs with the & character.
Thank you for this code, it is the best javascript solution I have found yet.
You are correct of course. This was written for a Domino application where the first parameter after the ? can always be ignored. Thanks for pointing it out though.
Matt
Hi
Nice work and i have saved the same thing as seperate java script file and i am calling that script through right click IE menu , It’s not working there why? ie. It’s not returning the URL ?
http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5N3GK5/$FILE/huh.gif“>
Not sure what the problem is. If you create a shortcut with this as a value:
javascript:alert(document.location.href)
It seems to work fine (i.e. you get a prompt with the current URL in it) so it should just be a matter of changing to code to do what you want from there.
Hey Tom,
I was getting syntax errors when I called the function from a form:
onLoad=”document.myForm.myfield.value = getURLParam(‘id’)”
The breakthrough was that I used single quotes instead of double quotes in the parameter I was passing, because of the external double quotes.
OK,
nice code by the way I’m working with something very similar, I’m not a javascript kind of person so go easy 🙂
I’m trying to do the same thing but passing an array in the params. i.e.
blah.cgi?foo=bar&foo=bah&foo=baz&feh=bam
So I end up with foo=(bar,bah,baz)&feh=(bam)
can anyone point me in the right direction?
It should be no problem psyber. Just don’t use the brackets. Use my code as is and then once you have the value of the parameter called “foo” (which will be a string with the value “bar,bah,baz”), you then just need to “split” the sting into an array:
var strValue = getURLParam(“foo”);
var myArray = strValue.split(“,”);
Hope this helps
Matt
There is a bug on the script or ruther the way your are defining a URL parameter is not actually the formal definition of URL parameter. A URL parameter is anything after the ? in the URL
The bug is that it wont find id in the the following URL
“.htm?id=testid¶m2=foo”
small modification to your code Matt:
just changed the first two occurences of & to ?
—————————————————————————
function getURLParam(strParamName){
var strReturn = “”;
var strHref = window.location.href;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)).toLowerCase();
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].indexOf(strParamName + “=”) > -1 ){
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
break;
}
}
}
return strReturn;
}
Giorgos,
As mentioned in the first two comments this function was written for a Lotus Domino application where the first parameter after the ? can always be ignored (it is an internal server parameter). However, it seems that most people coming here these days are not Domino heads so I have updated the function to reflect a more generic requirement.
Matt
Fantastic and simple to implement! I’ve been searching for this solution for months.
I’m Perl efficient and Javascript challenged. Unfortunate for me, the site owner requested a complex javascript menu. In order to store the javascript menu source outside the html file, I needed to pull a value from the URL params before loading the javascript menu arrays.
The address I entered above is the active site for Quantity Postcards. The URL where the new site is being tested is http://www.qpfans.com/catalog/psdbi/intro.html?TEMP_PARAM1=retail“ rel=”nofollow”>http://www.qpfans.com/catalog/psdbi/intro.html?TEMP_PARAM1=retail
Thank you, Matt, for using the Internet to share your knowledge. I will include your name and a site link.
Ashford
NOTICE:
The variable name should be lower cases. I had a variable link.asp?SomethiNG=1234 and with
getURLParam(‘SomethiNG’); // DOES NOT WORK
getURLParam(‘something’); // WORKS
Hope it helps
<script language=”JavaScript”>alert();</script>
Very fine .
Hi
I am new to javascript.
Where is the code placed on the html page?
ta
James
Hi James,
You can place Javascript anywhere in the HTML as long as it is surrounded with:
<script language=”javascript”>
//Your script goes here
</script>
Thant being said normally JS will be placed in the HTML header or in a seperate file which would be referenced using:
<script language=”javascript” src=”myscript.js”></script>
Hope this helps.
Matt
Thank you very much! I’m lookine for url parsrer for few days already! I’ve got completely mad!
Thanks, your function helped me a lot, you´re welcome to come to México anytime.
Wow. Thanks! I’ve looked everywhere for a good javascript version of the php $_GET. This works wonderfully! Well done!!
http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5N3GJN/$FILE/cool.gif“>
Hello, just a little improvment …
You should also use lowercase for the parameter of your function …
line -> if (aQueryString[iParam].indexOf(strParamName.toLowerCase()+ “=”) > -1 ) .. or a call to getUrlParam(‘Foo’) won’t work in a url …?Foo=bar….
I am having troubles getting it across frames.
[frame 1]
[frame 2]
how can i read the url from frame 1 in frame 2?
This is a little improvement when using frames
function GetURLParam(strParamName,FrameNaam)
{ var strReturn = “”;
var strHref = parent.frames[FrameNaam].location.href;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)).toLowerCase();
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if ( aQueryString[iParam].indexOf(strParamName + “=”) > -1 )
{ var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
break;
}
}
}
return strReturn;
}
Hi guys, I’ve got a little javascript question here, i have used your script to get the url parameter i want. This is the url:
blababla/en/index.php?frames=&views=statistics(1460)&functions=&elementId=712&action=browse
so i get the views in return as a value: statistics(1460)
but then, how can i get only the number out of it? so as a result tot get 1460 instead of statistics(1460) ??
Thanks for your time 🙂
statistics = “statistics(1460)”;
stat2 = statistics.split(“statistics(“);
statistics = stat2.join(“”);
stat2 = statistics.split(“)”);
statistics = stat2.join(“”);
alert(statistics);
I know there’s probably a much better and simpler was to do this (which i don’t know yet), but this should work…
And here is the simple way… (sorry for double post)
views = getURLParam(‘views’);
viewsnumber = views.substring(views.indexOf(“(“)+1,views.indexOf(“)”));
Excelente codigo solo le cambie algunas cosas para usarlo con paginas ASP
<script language=”JavaScript” type=”text/javascript”>
function getURLParam(strParamName){
var strReturn = “”;
var strHref = window.location.href;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)).toLowerCase();
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].indexOf(“=”) > -1 )
{
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
break;
}
}
}
return strReturn;
}
</script>
Gracias MATT
i’m trying to display an image header on a webpage accordingly to a param in the URL?
I’m trying to figure it out, but… can anyone help me with this?
Thank you… 🙂
i got, index.php?storytopic=3
want to show a diff images in same place for
if storytopic=1, 2 or 3….
Working.
function getURLParam(strParamName){
var strReturn = “”;
var strHref = window.location.href;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString =
strHref.substr(strHref.indexOf(“?”)).toLowerCase();
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (
aQueryString[iParam].indexOf(strParamName + “=”) > -1 ){
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
break;
}
}
}
return strReturn;
}
var topic = getURLParam(“storytopic”);
switch(topic)
{
case “1”:
document.writeln(‘<img src=”image1.jpg”>’);
break;
case “2”:
document.writeln(‘<img src=”image2.jpg”>’);
break;
case “3”:
document.writeln(‘<img src=”image3.jpg”>’);
break;
default:
document.writeln(‘<img src=”default.jpg”>’);
break;
}
This is a great way to get URL parameters using javascript but it is somewhat flawed. For example, one problem is that if you have an anchor in your URL it will be considered as part of the value for one of your parameters. Take the URL http://www.example.com/t.htm?p=1&r=2#top for an example. Using the function on this page if you try to get the value for the ‘r’ parameter it will give you ‘2#top’. For a more elegant solution see http://www.netlobo.com/url_query_string_javascript.html“ rel=”nofollow”>http://www.netlobo.com/url_query_string_javascript.html which deals with this problem and others by using Regular Expressions.
Hello
What happens if the parameter from the URL is a file
posted by an HTML form ?
Regards
Ignasi
Don’t you think that in php this is the good way:
$q = $_GET[‘M_RECIPE_ID’];
cool… now i can control ajax in a page using this your script
http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5MZVLS/$FILE/biggrin.gif“>
*jingkrak2 seneng*
I am new to javascript and would like to putt out a value of the existing URL and use it as a value in a new link on the page. After I add the code to the page, how do I get the value and use it in the new URL?
The is a (in my opinion) severe bug in this routine. It does NOT compare the full parameter names. If you set a parameter fooID=12 in the URL and AFTER that another parameter oID=baz you will get “12” as the result when looking for the oID parameter.
You should (in my opinion) compare the entire parameter name, “indexof” is NOT enough.
Just a few lines of code to show a possible solution to this problem:
…
if ( strHref.indexOf(“?”) > -1 ){
// remove the question mark!
var strQueryString = strHref.substr(strHref.indexOf(“?”)+1);
var aQueryString = strQueryString.split(“&”);
var cmpstring = strParamName + “=”;
var cmplen = cmpstring.length;
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
// Keep the difference between:
// fooID=…
// oID=…
// if (aQueryString[iParam].indexOf(strParamName + “=”) > -1 ){
if (aQueryString[iParam].substr(0, cmplen) == cmpstring ){
var aParam = aQueryString[iParam].split(“=”);
…
Hi
Regular expressions is the best tool for this problem pattern. IMHO the best solution is the one at at http://www.netlobo.com/url_query_string_javascript.html“ rel=”nofollow”>http://www.netlobo.com/url_query_string_javascript.html (mentioned earlier)
Great Post….
Nice work around for cross domain ifram calls…
Great post mate !
Really simple light and useful, u spare me much time.
cheers
Nice! I´ve made something similar, but your function is far more lighter and easier. Thanks for sharing!
Hey guys, how about this:
var _GET={};
for(var m, v=location.href.split(/[\?\&]/), k=v.length-1;k>0;k–)
_GET[(m=v[k].split(/[\=]/))[0]] = m.length>1?decodeURI(m[1]):””;
Now you can access the url variables this way:
alert(_GET.variablename)
var _GET={};
for(var m, v=location.href.split(/[?&]/), k=v.length-1;k>0;k–)
_GET[(m=v[k].split(/[=#]/))[0]] = m.length>1?decodeURI(m[1]):””;
Tuned it a bit so it wont mess up with a terminating #
Just reading some comments above, amazing how much bloat people can type for such a trivial problem. If you want your _GET object to have always lowercase parameter-names use this:
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]):””;
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)==a)?[]:{}, n=a.replace(/^[“\’](.*)[“\’]$/,”$1”);
n!=’-1′?o[n]=v:o[o.length]=v;
}
Note to moderator: Sorry, made a codetypo in the previous post please remove it and this line
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)==a)?[]:{}, n=a.replace(/^[“\’](.*)[“\’]$/,”$1”);
n!=’-1′?o[n]=v:o[o.length]=v;
}
How to transfer data from one html document form to another html document form.What is the procedure?
http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5MZVLY/$File/smile.gif“ />
Nice code!
http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5MZVLS/$File/biggrin.gif“ />
thank you!{ http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5MZVLS/$File/biggrin.gif“ rel=”nofollow” target =”blank”>Link }
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<script language=”javascript”>
function getURLParam(strParamName){
var strReturn = “”;
var strHref = window.location.href;
if ( strHref.indexOf(“?”) > -1 ){
var strQueryString = strHref.substr(strHref.indexOf(“?”)).toLowerCase();
var aQueryString = strQueryString.split(“&”);
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + “=”) > -1 ){
var aParam = aQueryString[iParam].split(“=”);
strReturn = aParam[1];
break;
}
}
}
return unescape(strReturn);
}
</script>
</body>
</html>
{ http://localhost/test.php?id=testid“ rel=”nofollow” target =”blank”>Link }
…why doesn’t this work?
I need to pass a filename on to a viewer page:
<a href=”view.html?/x/pix1.jpg”>pix1</a>
and then read the value into a variable, for example ppp, that I can use to display that picture, for example
<img src=”<!–#echo var=”ppp” –>”>
What code do I need to read the value and stuff it into ppp ?
Thanks
Helmut
XPages is making life easier by using XSPContext and getUrlParameter.
Anyhow thanks.
Thank you, this came very much in handy.
hey thanks a lot for the great code..it works like a charm :)…you saved me so much time 🙂
Very nice….
HI,
thank you for the piece it helped me a lot.