It seems there's no easy and built-in way to check whether an url contains a query string and if it does, get it. The approaches I found so far rely on "url.indexOf("?")" and regex. Are these the only ways, isn't in Javascript there anything like "url.queryString" property?
Asked
Active
Viewed 2,401 times
2
-
4There is not... http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – JBux Dec 20 '15 at 12:09
-
You can use a custom function like [this example](http://gomakethings.com/how-to-get-the-value-of-a-querystring-with-native-javascript/) – Alex Char Dec 20 '15 at 12:12
-
If you're not afraid of 3rd party dependencies, try this: https://github.com/sindresorhus/query-string – Victor Nițu Dec 20 '15 at 12:12
1 Answers
1
No there is no direct way to do that, or no built in functionality is provided by JS to do this, but there are many relatively straight forward approaches to do this, Like this one:
var field = "anyquery";
var _status = window.location.href.indexOf('?' + field + '=');
if(_status!=-1){
// Field Exists!
}
Or even this one: (Source)
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
You can check using getUrlVars().hasOwnProperty("anyquery");
and the value can be fetched using getUrlVars().anyquery
and the array
of all the query
can be Object.keys(getUrlVars());