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:
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:The reason I'm posting an answer too is to briefly explain how the
&&
operator works: givenexpr1 && expr2
, the&&
operator "Returnsexpr1
if it can be converted to false; otherwise, returnsexpr2
."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:Another generic approach
Call it like this.