Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting parameters out of the url

Status
Not open for further replies.

secretsquirrel

Programmer
Mar 22, 2001
202
GB
hi,

i've got a url with a load of parameters on the end of it. i want to be able to retrieve one of those parameters and display something different in the page depending on it's value.

i'll write some pseudo code to explain what i'm on about:

the url is something like this (with different values for 'area')...

Code:
[URL unfurl="true"]http://blah[/URL] blah blah/page?lang=AEN&country=AUS&area=123

and i basically want to be able to do the following...

Code:
if(area == "123")
{
    display something
} else {
    display something else
}

problem is i have no idea how to access the parameter 'area'

can anyone point me in the right direction?

thanks in advance,

ss...
 
squirrel,

JavaScript's split() function will help you. If you use it on a string and tell it what character you want to split on, it will return to you an array of items... one for each part of the string on either side of the named character.

For example:

Code:
var urlArray = document.location.href.split("?");

urlArray will contain two elements/indeces (given your example). urlArray[0] will equal " blah blah/page" and urlArray[1] will equal "lang=AEN&country=AUS&area=123". Notice that neither contains the "?".

So you can grab just the parameter list by:

Code:
var paramList = (document.location.href.split("?"))[1];

...or, if you made urlArray like I showed above...

Code:
var paramList = urlArray[1];

The parameters are separated by ampersands (&'s), so:

Code:
var parameters = paramList.split("&");

Each of the indeces in parameters contain a name/value pair (e.g., "area=123");

To then do the check you want, you can:

Code:
for(var i=0; i<parameters.length; i++)
{
 if(parameters[i].indexOf("area=") == 0)
 {
  if((parameters[i].split("="))[1] == "123")
   /display something
  else
   //display something else
 }
}

'hope that helps!

--Dave
 
LookingForInfo,

That's a good explanation. But don't forget to unescape the data:
Code:
var paramList = unescape((document.location.href.split("?"))[1]);
That'll put all your special characters back into the submitted values.

-kaht

banghead.gif
 
If you want to convert the parameters to window variables (which is what your code looked like to me) then this should do it:
Code:
var p=location.search.substring(1).replace(/\+/g,' ').split("&");
for(var i=0;i<p.length;i++){
  v=p[i].split("=");
  window[unescape(v[0])]=unescape(v[1])
}

Adam
while(ignorance){perpetuate(violence,fear,hatred);life=life-1};
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top