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?
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.
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.
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? 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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With