Jquery how to check if url contains a word?

I want to check if url contains a directory of words.

This is what I'm trying ...

$(document).ready(function () { if (window.location.href.indexOf("catalogue")) { $("#trail").toggle(); } }); 

The site URL may be ...

 http://site.co.uk/catalogue/ 

or

 http://site.co.uk/catalogue/2/domestic-rainwater.html 

and etc.

But that will not work. Can anyone point out where I'm wrong?

+8
source share
2 answers

Try:

 if (window.location.href.indexOf("catalogue") > -1) { // etc 

indexOf does not return true / false, it returns the location of the search string in the string; or -1 if not found.

+29
source

Since the OP is already looking for a logical result, an alternative solution could be:

 if (~window.location.href.indexOf("catalogue")) { // do something } 

Tilde ( ~ ) is a bitwise NOT operator and performs the following actions:

~n == -(n+1)

Simply put, the above formula converts -1 to 0, making it false, and everything else becomes a non-zero value, which makes it true. Thus, you can view the results of indexOf as logical.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#(Bitwise_NOT)

+2
source

Source: https://habr.com/ru/post/913712/


All Articles