Retrieve URL Query String with JQuery

Here’s a quick and easy way to get a query string from your URL using jquery. Suppose you have the following URL: www.myurl.com?page=mypage. Use the code below to retrieve page=mypage. Of course this can be any name/value pair…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script type="text/javascript">
  function getQuerystring(key, default_){
    if (default_==null) default_="";
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if(qs == null)
      return default_;
   else
     return qs[1];
 }	
 var urlString = getQuerystring('page');
 
  $(document).ready(function(){
    if ( urlString == 'mypage' ) {  
      //Do something with jquery here
    }
  });
</script>

3 Responses to “Retrieve URL Query String with JQuery”

  1. Jon B

    What programming language is the page written in?

  2. Tim

    I have a url query string that was set up for us previously and i am trying to get the info that string pulls to insert in a form that I have.
    The URL query string is: registration?memid=300&uname=unamehere

    Is there a simple code I can use on the registraion page to insert this info into the two fields i need it?

  3. Ben Sky

    Nice bit of code, helped me out on a current project, thanks!

Leave a Reply

CAPTCHA Image
*