How to redirect to a page if url does not contain a word?

0

I wish that if there was no string in the url, it would redirect to a page. This is what I tried

$(document).ready(function () {
    if(!window.location.href.indexOf("www") > -1) {
        var link = window.location.href;
        var ver = link.substr(link.indexOf("index.php"));
        window.location.href="https://www.famalicaocanal.pt/"+ver;
    }
});

With the code above it works but it always keeps refreshing the page even if there is www in the url.

    
asked by anonymous 15.02.2018 / 21:29

2 answers

1

The exclamation mark ! serves to turn a false condition into true and vice versa.

To compare with -1 , you should remove this ! from the beginning.

$(document).ready(function () {
    if(window.location.href.indexOf("www") < 0) {
        var link = window.location.href;
        var ver = link.substr(link.indexOf("index.php"));
        window.location.href="https://www.famalicaocanal.pt/"+ver;
    }
});

As it stands, it is transforming window.location.href.indexOf("www") to 0 or 1 (false or true respectively) and always 0 and 1 will be greater than -1, making its true condition always.

    
15.02.2018 / 21:34
1

You can use this form too:

$(document).ready(function () {
   if(location.href.indexOf("www") != -1) {
      var link = location.href;
      var ver = link.substr(link.indexOf("index.php"));
      location.href="https://www.famalicaocanal.pt/"+ver;
   }
});

window.location.href and location.href are the same thing. indexOf can return two types of values:

  • -1 , when it does not find occurrences and
  • 0 or positive numbers , when there are occurrences (depending on the position of the string ).
  

Another note is not to use the word link to name objects   (in your case, a variable). JavaScript has a list   reserved words and link is between them. Although it may work   as a variable in your code, the recommendation is not to use words   reserved for this purpose.

    
15.02.2018 / 22:19