javascripthtmlurlwindow.location

How to implement wildcards for window.location.pathname


I have the following code and I would like to make the function work on any URL containing "blog" instead of a specific URL. Please help me with the correct syntax, thanks.

window.setTimeout(function() {
  if (window.location.pathname != '/home/legal-documentation' &&
    window.location.pathname != '/home/blog/australian-business-news'
  ) {
    erOpenLoginRegisterbox(jQuery);
  }
  return false;
}, 1000);

Solution

  • I think you are looking for String.prototype.indexOf(). It will return -1 if it does not find the string it is passed, so testing for -1 seems to correlate with your approach. Furthermore, to be on the safe side, in case you also want to exclude blog in a case-insensitive manner (in other words, you want to test for Blog, blog, BLOG, etc.), I refer to pathname as though it were uppercase (String.prototype.toUpperCase()), and then compare it to 'BLOG'

    window.setTimeout(function() {
        if (window.location.pathname.toUpperCase().indexOf('BLOG') === -1) {
            erOpenLoginRegisterbox(jQuery);
        }
        return false;
    }, 1000);