1

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?

3 Answers 3

8

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I tried something like this initially but didn't quite get the syntax right.
5

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)

1 Comment

+1'ed for the explanation. I was just about to post that as a comment.
4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.