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

Asked

Viewed 50 times

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 above code it works but it always continues to refresh the page even if it exists www at the url.

2 answers

1


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

To compare with -1, you must remove that one ! 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;
    }
});

The way it is, he’s turning window.location.href.indexOf("www") 0 or 1 (false or true respectively) and always 0 and 1 will be greater than -1, making your condition always true.

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. Already the indexOf can return two types of values:

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

Another observation is not to use the word link to name objects (in your case, a variable). Javascript has a list of reserved words and link is among them. Although it may work as a variable in your code, the recommendation is not to use words reserved for that purpose.

  • Thank you for your reply! I will in future not use the word link and the like to name variables! + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.