In the question how to check if the url contains a given string. Javascript/jquery
the answer checks if the url contains a given string. I want to extend this to check if it contains two things name=franky && gender=male. I tried
if(window.location.href.indexOf("name=franky" && "gender=male") > -1)
which appeared to work initially, but with further testing I have found it seems to work if only one of name or gender is present. Where am I going wrong here?
You could break it into two parts and call indexOf twice instead of trying to check for both strings in the same call. Something like this:
if(window.location.href.indexOf("name=franky") > -1 &&
window.location.href.indexOf("gender=male") > -1)
The .indexOf()
function only looks for a single string. To test for two strings you need two calls to .indexOf()
as per Christofer's answer:
if(window.location.href.indexOf("name=franky") > -1 &&
window.location.href.indexOf("gender=male") > -1)
The reason I'm posting an answer too is to briefly explain how the &&
operator works: given expr1 && expr2
, the &&
operator "Returns expr1
if it can be converted to false; otherwise, returns expr2
."
What does "converted to false" mean? Basically null
, undefined
, 0
, NaN
and ""
(empty string) are "falsy" and will be "converted to false". non-zero numbers, non-empty strings and any object are "truthy" and will be converted to true.
That means when you said "name=franky" && "gender=male"
the &&
operator tests the first operand, finds that (in this case) it can't be converted to false, so it returns "gender=male"
. So the reason your code seemed to work some of the time is that in effect it was doing this:
if(window.location.href.indexOf("gender=male") > -1)
Another generic approach
function CheckIfAllQueryStringsExist(url, qsCollection) {
for (var i = 0; i < qsCollection.length; i++) {
if (url.indexOf(qsCollection[i]) == -1) {
return false;
}
}
return true;
}
Call it like this.
var myUrl = window.location.href;
var queryStrings = ["name=franky", "gender=male"];
var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);