Go4Expert

Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/articles/javascript-tutorials/)
-   -   Getting Query parameters in Javascript (http://www.go4expert.com/articles/getting-query-parameters-javascript-t2163/)

pradeep 7Dec2006 18:26

Getting Query parameters in Javascript
 
We sometimes require to get the query parameters of an URL in JavaScript, here's how we can do that.

Code: JavaScript

// get the current URL
 var url = window.location.toString();
 //get the parameters
 url.match(/\?(.+)$/);
 var params = RegExp.$1;
 // split up the query string and store in an
 // associative array
 var params = params.split("&");
 var queryStringList = {};
 
 for(var i=0;i<params.length;i++)
 {
     var tmp = params[i].split("=");
     queryStringList[tmp[0]] = unescape(tmp[1]);
 }
 
 // print all querystring in key value pairs
 for(var i in queryStringList)
     document.write(i+" = "+queryStringList[i]+"<br/>");

Example usage:
HTML Code:

<script language='JavaScript'>
 // get the current URL
 var url = window.location.toString();
 //get the parameters
 url.match(/\?(.+)$/);
 var params = RegExp.$1;
 // split up the query string and store in an
 // associative array
 var params = params.split("&");
 var queryStringList = {};
 
 for(var i=0;i<params.length;i++)
 {
        var tmp = params[i].split("=");
        queryStringList[tmp[0]] = unescape(tmp[1]);
 }
 
 // print all querystring in key value pairs
 for(var i in queryStringList)
        document.write(i+" = "+queryStringList[i]+"<br/>");
 </script>


Output:
Code:

ab = pradeep
 site = go4expert


ankit_khandelwal16 28Dec2010 12:33

Re: Getting Query parameters using Javascript
 
Thanks Buddy
It really helped me to solve my problem.
Can you help me more little on this how to make any url from this to get any document of that query

rameshb 28Dec2010 14:23

Re: Getting Query parameters using Javascript
 
Thank you my friend for the post .

ulfemsoy 23Oct2011 13:03

Re: Getting Query parameters using Javascript
 
Nice.

To get a specific named argument in the query you could also do it the following way:
lazerwire.com/2011/10/javascript-get-url-query-argument.html

Remember to url decode the value using the "unescape" method in JavaScript.


All times are GMT +5.5. The time now is 11:30.