Tuesday, March 11, 2008

fetchNVPValue - routine to extract a value from a querystring

There are probably more efficient - and more bullet-proof - ways to do this, but figured I had better capture this before I forgot that I wrote it.

Shannon Norrell

////////////////////////////////////////////////////////////////////////////////
//
// fetchNVPValue( string aNVPName, string aURL )
//           Extracts the value of a Named Value Pair (NVP) from a URL
//       eg: fetchNVPValue( "name", "http://mypage.com?id=123&name=Shannon&foo=bar" ) returns "Shannon"
//
////////////////////////////////////////////////////////////////////////////////
function fetchNVPValue( aNVPName, aURL ) {
  var retVal = "";
  var bItsInThereSomeWhere = (aURL.toLowerCase().indexOf(aNVPName) > -1);
  // If we have a URL, a name to look for and it's in there somewhere ...
  if ( aNVPName && aURL && bItsInThereSomeWhere ) {
    var theURL = aURL.toLowerCase().replace(/\+/g, ' ');    // Turn all '+' signs back into spaces, if applicable
    var args = theURL.split("&");
    for (var i=0;i<args.length;i++) {
      var nvp = args[i].split("="); // Break out each argument out into a NVP
      var name  = unescape(nvp[0]);
      if (name==aNVPName) {
        retVal = nvp[1];
        break;
      }
    }
  }
  // If we still haven't extracted it and it's in there somewhere, the Named value follows a "?" in the URL, rather than a &
  if (( retVal == "") && bItsInThereSomeWhere) {
    if (aURL.toLowerCase().indexOf("?" + aNVPName) > -1) {
      retVal = aURL.split("?")[1].split("=")[1];
    }
  }
  return retVal;
}

No comments: