Sometimes we get the important data through query string but question is of getting query string values in javascript or jquery because we need these values at client side. Even we can do it by using only javascript also.
For getting values, we need to parse the query string as follows:
1. Using regular expression in javascript
1 2 3 4 5 6 | function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } |
We need to call it like :
1 | var patId = getParameterByName('patId '); |
Here we can pass the key name for which we want to parse the value from query string.
2. Using simple javascript
If we want we can get the whole query string as object and then access its value by its key like :
1 2 3 4 5 6 7 8 9 | function get_query(){ var url = document.location.href; var qs = url.substring(url.indexOf('?') + 1).split('&'); for(var i = 0, result = {}; i < qs.length; i++){ qs[i] = qs[i].split('='); result[qs[i][0]] = decodeURIComponent(qs[i][1]); } return result; } |
In above given code, steps are as follows :
1. Getting url
2. Parsing query string by splitting url
3. Looping through each and every key in parsed query string
4. Storing every key and its value as an object
5. Return the object
We can call the function and get the object in an variable as follows :
1 | var result = get_query(); |
For the query string x=5&y&z=hello&x=6
this returns the object:
1 2 3 4 5 | { x: "6", y: undefined, z: "hello" } |
3. Using jQuery :
1 2 3 4 5 6 7 8 9 10 11 12 13 | (function($) { $.QueryString = (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('='); if (p.length != 2) continue; b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })(window.location.search.substr(1).split('&')) })(jQuery); |
Usage :
1 | $.QueryString["param"] |