Tuesday, August 28, 2012

Parsing URL query string in your web page (JavaScript)

This is a quick function I wrote that will parse out the query string name=value pairs and return an object with those names defined.  If no query parameters were supplied, the function returns undefined.

   1:  function getDocumentQueryVariables() {
   2:   
   3:      // Return undefined if there are no query variables
   4:      if (window.location.search.length == 0)
   5:          return undefined;
   6:      var objVars = {};
   7:      var vars = window.location.search.substring(1).split('&');
   8:      for (var i = 0; i < vars.length; i++) {
   9:          var pair = vars[i].split('=');
  10:          if(pair.length == 2) {
  11:              objVars[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  12:          }
  13:      }
  14:      return objVars;
  15:  }

For example, you could have “?search=something” at the end of your web page.  This function will pass back an object with a property called “search” set to whatever value was supplied.

For example

   1:      // Exit if there's no query variable(s)
   2:      var Q = getDocumentQueryVariables();
   3:      if (Q === undefined)
   4:          return;
   5:   
   6:      // Perform search if we have one
   7:      if (Q.search) {
   8:          
   9:      }

No comments: