jQuery – Get URL Query String

We could also get the URL query string in jQuery.

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

 

Try the example below.

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript">
      $.extend({
        getUrlVars: function(){
          var vars = [], hash;
          var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
          for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
          }
          return vars;
        },
        getUrlVar: function(name){
          return $.getUrlVars()[name];
        }
      });
    </script>
  </head>
  <body>
    <h1>Hello World</h1>
    <script type="text/javascript">
      // example: http://www.example.com/index.html?name=ykyuen&age=27

      // Get the urlVars object which store all url query strings
      var urlVars = $.getUrlVars();
      alert(urlVars['name']);     // ykyuen
      alert(urlVars['age']);      // 27

      // Get the specific url query string directly
      alert($.getUrlVar('name')); // ykyuen
      alert($.getUrlVar('age'));  // 27
    </script>
  </body>
<html>

 

Done =)

Reference:

About these ads

3 thoughts on “jQuery – Get URL Query String

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s