jQuery如何检查URL是否包含某个单词?

12

我想要能够检查URL是否包含单词“catalogue”。

这是我的尝试...

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

该网站的URL可能是...

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

但它不起作用。请问有人可以指出我哪里错了吗?


1
将 if (window.location.href.indexOf("catalogue")) 更改为 if (window.location.href.indexOf("catalogue") > -1)。 - rt2800
http://stackoverflow.com/questions/897903/condition-to-test-if-a-word-exists-in-window-location-href - Richard
你尝试过.indexOf()文档了吗? - nnnnnn
https://dev59.com/AUzSa4cB1Zd3GeqPrPzG - Richard
3个回答

41

尝试:

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

indexOf 不会返回 true/false,它会返回字符串中搜索字符的位置;如果未找到,则返回 -1。


1
!= -1 对于 indexOf 来说会更好。 - Selvakumar Arumugam
1
@Vega 我不确定我同意它更好。结果是相同的 > -1 需要少一个字符。如果这段代码在每天有100万个请求的网站上,那么可以节省相当多的带宽! :-) - Simon

3

考虑到原帖作者已经在寻找布尔型结果,另一种解决方案是:

if (~window.location.href.indexOf("catalogue")) {
    // do something
}
~是位运算符NOT,它执行以下操作:~n == -(n+1)。简单来说,上述公式将-1转换为0,使其为假值,而其他任何值都变成一个非零值,使其为真值。因此,您可以将indexOf的结果视为布尔值。参考链接

2
您可以简单地使用includes()。请参考以下代码。
$(document).ready(function () {
    if(window.location.href.includes('catalogue')) {
        $("#trail").toggle();
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接