65.9K
CodeProject is changing. Read more.
Home

JScript Querystringer

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jan 30, 2002

viewsIcon

89854

Here's some simple JScript that returns the value part of a name-value querystring pair from inside an HTML page.

Introduction

One of the things that can get overlooked in web development is the fact that you can pass parameters to HTML pages without having to bounce a redirect statement off the server. This can be pretty useful if the HTML page is a generic that loads various xml files based on that parameter (like a product details page with a productID being passed). Here's the code:

function retVal(sName)
{

  /*
   get last loc. of ?
   right: find first loc. of sName
   +2
   retrieve value before next &
  
  */
  
  var sURL = new String(window.location);
  var iQMark= sURL.lastIndexOf('?');
  var iLensName=sName.length;
  
  //retrieve loc. of sName
  var iStart = sURL.indexOf('?' + sName +'=') //limitation 1
  if (iStart==-1)
        {//not found at start
        iStart = sURL.indexOf('&' + sName +'=')//limitation 1
		if (iStart==-1)
		   {//not found at end
		    return 0; //not found
		   }   
        }
        
  iStart = iStart + + iLensName + 2;
  var iTemp= sURL.indexOf('&',iStart); //next pair start
  if (iTemp ==-1)
		{//EOF
		iTemp=sURL.length;
		}  
  return sURL.slice(iStart,iTemp ) ;
  sURL=null;//destroy String
}


alert( retVal('mynewname'));

Usage:

Save the code into a normal HTML page and call it like this:

mypage.htm?mynewname=testvalue

and "testvalue" should be returned in the alert box. The "mynewname" is just a literal and can be replaced with any querystring name that has a value related to it.