Graphic Design ServicesandPortfoliobyPhillip DodsonofVisional Echoes
July 7, 2007 at 7:08 pm

Query String Value Getter Function

» Filed Under » javascript

This function will take a query string (or use the current URI if no string is supplied) and return the value of the chosen argument.

Code

function GetQueryValue(k,q) // Key, Query String
{
   q=q||location.href;  // uses current uri if no query is supplied
   var tmpNdx=q.indexOf('?');
   if (tmpNdx!=-1) // If string has query information
   {
      q=q.slice(tmpNdx+1); // Remove all information except for query
      q=q.split('&');      // Create array of key/value pairs
      for (var i=0;i<q.length;i++)
      {
         var p=q[i].indexOf('=');
         if (p>0)
         {
            var thisk=q[i].substring(0,p);
            if (thisk==k) return q[i].substring(p+1); // return value
         }
      }
      return null; // If key doesn't exist, return null	
   } else {
      return null; // If no query information, return null
   }
}

Returns

  • string | value of argument if exists
  • null if argument doesn’t exist

Prototype

GetQueryValue(string key[, query string])

Note that the query string argument is optional. If no string is supplied, script will use the address of the page.

Samples

<script type="text/javascript" src="GetQueryValue.js"></script>   // include the script
<script type="text/javascript">
   var myStr='http://www.mywebsite.com?var1=foo&var2=bar';
 
   alert(GetQueryValue('var2',myStr));     // alerts bar
   alert(GetQueryValue('somevar',myStr));  // alerts null
   alert(GetQueryValue('myvar'));              //  Searches your current URI and returns myvar if it exists
</script>

Download

You can download the script here.