This is an extension that I have been using to parse URL search strings and hash codes. I thought that I would share it with the world, and if the world has a better method I hope that someone shares it with me.

/*!
 * jQuery URL variable extensions
 *
 * Copyright (c) 2010, Christopher Stoll
 */
jQuery.extend({
  // return an associative array with url query parameters
  urlVars: function() {
    // we have a search string
    if (window.location.search){
      // drop the ? and then split on &
      var ary=window.location.search.substr(1).split("&");
      var qStr=[];
      // for each set
      for (i=0;i<ary.length;i++) {
        // split on = and put that array back in original
        ary[i]=ary[i].split("=");
        // unescape the first item and restore spaces
        ary[i][0]=unescape(ary[i][0].replace(/\+/g," "));
        // if there is a second item
        if (ary[i][1]) {
          // unescape the second item and restore spaces
          ary[i][1]=unescape(ary[i][1].replace(/\+/g," "));
          // we have a pair to return
          qStr[ary[i][0]]=ary[i][1];
        }
      }
      // return the pairs
      return qStr;
    // no search string
    } else {
      // return an empty array
      return [];
    }
  },



  // return a string value for a query parameter
  urlVar: function(vnam) {
    var vval=$.urlVars()[vnam];
    if(vval != undefined) {
      return vval;
    } else {
      return "";
    }
  },
  // return a string value of the first hash
  urlHash: function() {
    if(window.location.hash){
      var ary=window.location.hash.substr(1).split("#");
      return ary[0];
    } else {
      return "";
    }
  },
  // return an array with all the hashes
  urlHashes: function() {
    if(window.location.hash){
      return ary=window.location.hash.substr(1).split("#");
    } else {
      return [];
    }
  },
  // return true if the hash is present
  hasHash: function(hnam) {
    if(jQuery.inArray(hnam, $.urlHashes()) > -1) {
      return true;
    } else {
      return false;
    }
  }
});

Tags: Blogger JavaScript jQuery Code

Published: 2010-03-23