Saturday 21 March 2015

How can I get query string values in JavaScript and jQuery?

How can I get query string values in JavaScript and jQuery?

I want to get the values from the Query String (means from URL), values are dynamic but query string variable is constant.

Suppose, I have following URL:
http://www.example.com/country.php?id=10&c=country

Now, I want to get the value of following query string.
id //currently it is 10, but it is dynamic.
c //currently it is country, but it is dynamic.


Solution 1: Get the value of query string with JavaScript.
Step 1: Add following javaScript function in your page.
   
function getParam(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        result = regex.exec(location.search);
    return result === null ? "" : decodeURIComponent(result[1].replace(/\+/g, " "));
}

Step 2: Use getParam function to get the query string values. See below:
console.log(getParam('id'));
console.log(getParam('c'));



Solution 2: Get the value of query string with jQuery.
Step 1: Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

Step 2: Add following jQuery function in web page.
jQuery(document).ready(function(){
  $.getParamJquery = function(name, url) {
      if (!url) {
       url = window.location.href;
      }
      var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
      if (!results) { 
          return undefined;
      }
      return results[1] || undefined;
  }
  
});

Step 3: Use getParamJquery function to get the query String values. See below:
jQuery(document).ready(function(){
  console.log($.getParamJquery('id'));   
  console.log($.getParamJquery('c'));
}