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.

Leave a Comment

RSS feed for comments on this post. TrackBack URL

  1. Comment by Omar — October 1, 2007 @ 4:51 pm

    First query I’ve seen that demonstrates how to implement the retreived variables.

    I couldn’t get
    alert(GetQueryValue(’myvar’));
    to work for me, so instead I used this for myVar:

    var myStr=’\”‘ + top.window.location + ‘\”‘;

    Thanks for the script.

  2. Comment by Phil — October 1, 2007 @ 5:23 pm

    Hmmm that’s odd. So you called
    alert(GetQueryValue(’myvar’));
    And myvar was a query variable in your current URI?
    I will take a look at this later on.

Sorry, the comment form is closed at this time.