Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery how to check if url contains word?

I want to be able to check if url contains the word catalogue.

This is what i am trying...

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

The url of the site could be..

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

Or

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

etc.

But it doesn't work. Can somebody please point out where I'm going wrong?

like image 703
Beginner Avatar asked Apr 20 '12 09:04

Beginner


People also ask

How do I know if a URL has a specific word?

To check if the current URL contains a string in Javascript, you can apply the “test()” method along with the “window. location. href” property for matching the particular string value with the URL or the “toString(). includes()”, or the “indexOf()” method to return the index of the first value in the specified string.

How do I check if a URL contains a string?

Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() . Therefore, the argument of indexOf should be your search string.

How to check URL using jQuery?

The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The 'href' property returns a string with the full URL of the current page.

How do you check if the URL contains a given string in Java?

How do you check if the URL contains a given string in Java? You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring.


2 Answers

Try:

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

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

like image 128
Simon Avatar answered Sep 24 '22 14:09

Simon


Seeing as the OP was already looking for a boolean result, an alternative solution could be:

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

The tilde (~) is a bitwise NOT operator and does the following:

~n == -(n+1)

In simple terms, the above formula converts -1 to 0, making it falsy, and anything else becomes a non-zero value making it truthy. So, you can treat the results of indexOf as boolean.

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

like image 41
Martin James Avatar answered Sep 25 '22 14:09

Martin James