Hi,
How to extract QueryString from the URL in javascript?
Thank You!
Hi,
How to extract QueryString from the URL in javascript?
Thank You!
If you're referring to the URL in the address bar, then
window.location.search
will give you just the query string part. Note that this includes the question mark at the beginning.
If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:
url.substring(url.indexOf("?"))
That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.
You can easily build a dictionary style collection...
function getQueryStrings() {
var assoc = {};
var decode = function (s) { decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
assoc[decode(key[0])] = decode(key[1]);
}
return assoc;
}
And use it like this...
var qs = getQueryStrings();
var myParam = qs["myParam"];