WEBDOOD.COM

Tag: querystring

fetchNVPValue – a routine to extract a value from a querystring

by webdood on Mar.11, 2008, under Javascript, Software Development

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

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org