« Depressing or Impressive? | Main| Interesting if intimidating experience »

Get URL Parameter in Javascript

Category
Bookmark : del.icio.us  Technorati  Digg This  Add To Furl  Add To YahooMyWeb  Add To Reddit  Add To NewsVine 

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.

Comments

Gravatar Image1 - 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

Thank you, Matt, for using the Internet to share your knowledge. I will include your name and a site link.

Ashford

Gravatar Image2 - Wow. Thanks! I've looked everywhere for a good javascript version of the php $_GET. This works wonderfully! Well done!!

Gravatar Image3 - Thank you very much! I'm lookine for url parsrer for few days already! I've got completely mad!

Gravatar Image4 - 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

Gravatar Image6 - I set this script up at http://www.freewebs.com/pupnet/testinghap.htm using the URL http://www.freewebs.com/pupnet/testinghap.htm?happy=test doesnt change the value of the text field called 'happy', is there something I'm not doing right, is it my placement of the script itself or did I not edit everything int he script correctly?

Thanks,
-Tom

Gravatar Image7 - 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... :)

Gravatar Image8 - 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&param2=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;
}

Gravatar Image9 - 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

Gravatar Image10 - 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

Gravatar Image11 - 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 ?

Gravatar Image12 - <script language="JavaScript">alert();</script>

Gravatar Image13 - 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;
}

Gravatar Image14 - And here is the simple way... (sorry for double post)

views = getURLParam('views');
viewsnumber = views.substring(views.indexOf("(")+1,views.indexOf(")"));

Gravatar Image16 - 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 :)

Gravatar Image17 - 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

Gravatar Image18 - I am having troubles getting it across frames.
[frame 1]
[frame 2]
how can i read the url from frame 1 in frame 2?

Gravatar Image19 - i got, index.php?storytopic=3

want to show a diff images in same place for
if storytopic=1, 2 or 3....

Gravatar Image20 - 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?

Gravatar Image21 - Don't you think that in php this is the good way:

$q = $_GET['M_RECIPE_ID'];

Gravatar Image22 - 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

Gravatar Image23 - Hi I am new to javascript. Where is the code placed on the html page? ta James

Gravatar Image24 - 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 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 which deals with this problem and others by using Regular Expressions.

Gravatar Image25 - 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.

Gravatar Image26 - 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.

Gravatar Image27 - 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....

Gravatar Image28 - Very fine .

Gravatar Image29 - 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.

Gravatar Image30 - 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...

Gravatar Image31 - 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;
}

Gravatar Image32 - Hello

What happens if the parameter from the URL is a file
posted by an HTML form ?

Regards
Ignasi


Gravatar Image33 - Thanks, your function helped me a lot, you´re welcome to come to México anytime.

Gravatar Image34 - 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

Gravatar Image35 - cool... now i can control ajax in a page using this your script
*jingkrak2 seneng*

Gravatar Image36 - 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?

Gravatar Image37 - 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("=");
...

Gravatar Image38 - 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 (mentioned earlier)

Gravatar Image39 - Great Post....
Nice work around for cross domain ifram calls...

Gravatar Image40 - Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon Emoticon

Gravatar Image41 - Great post mate !

Really simple light and useful, u spare me much time.

cheers

Gravatar Image43 - Nice! I´ve made something similar, but your function is far more lighter and easier. Thanks for sharing!

Post A Comment

:-D:-o:-p:-x:-(:-):-\:angry::cool::cry::emb::grin::huh::laugh::lips::rolleyes:;-)

UKLUG

NO2ID - Stop ID cards and the database state

Email / MSN / Google Talk matthew.white@fclonline.com
AIM: whitemx
Skype: whitemrx

Hits since 03-Feb-2006