1

I have to show different divs based on what search terms are entered into my site. The URL will contain the search term entered, so I thought I could check for the string in the URL and show the div if there is a match.

For the Doufeu/doufeu part, the div will only show based on the first term. The code is below - it will only show if Doufeu is in the string, but not doufeu. Why?

Based on what I read here and here, I have tried the code below, and also using && instead of || because the second link explains the second condition is only read if the first one is false. I found this and also tried separating with a comma. None work for me though. Here is where I am now:

        <script type="text/javascript">
        $(document).ready(function(){

            if ((window.location.href.indexOf("searchTerm=Doufeu" || "searchTerm=doufeu") > -1)){
            $("#learn-doufeu").show();
        }

        else {
            $("#ci-guide").show();
        }
        });
        </script>

I know I could make a new if else condition and separate Doufeu from doufeu that way but surely there is a way to do it with OR.

Community
  • 1
  • 1
surfbird0713
  • 1,209
  • 2
  • 23
  • 45

3 Answers3

6

You are or-ing two strings together, rather than the results of indexOf. Do two separate calls instead:

if (window.location.href.indexOf("searchTerm=Doufeu") != -1 || window.location.href.indexOf("searchTerm=doufeu") != -1)

Possible a better way to do this would be to use a regular expression.

if (/searchTerm=[Dd]oufeu/.test(window.location.href)) {
    // do stuff
}
Matt Bryant
  • 4,841
  • 4
  • 31
  • 46
  • 2
    Also note that `||` on two strings just evaluates to the first truthy string, so `"searchTerm=Doufeu" || "searchTerm=doufeu"` is the ***exact*** same as just `"searchTerm=Doufeu"` in Javascript. – Paul Sep 10 '13 at 16:25
  • ooops you typed faster! and +1 for the regex (and I'd like to vote again because you didn't use `/searchterm=doufeu/i` – PA. Sep 10 '13 at 16:30
  • Thanks, this is a great working solution and your explanation helped me learn something new. I used the regex as I think that is cleaner. – surfbird0713 Sep 10 '13 at 18:16
0

your code does not reflect your intentions. Your code actually applies the OR operation || to the two strings not to the comparisons.

change the code to

if ( (window.location.href.indexOf("searchTerm=Doufeu") > -1) ||
     (window.location.href.indexOf("searchTerm=doufeu") > -1)    ){
PA.
  • 28,486
  • 9
  • 71
  • 95
0

I would suggest splitting the conditional statement as follows:

if (window.location.href.indexOf("searchTerm=Doufeu") > -1 || window.location.href.indexOf("searchTerm=doufeu") > -1))

This should allow for both comparisons while keeping the check in a single if.