Javascript jquery如何检查url是否包含单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10243576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery how to check if url contains word?
提问by Beginner
I want to be able to check if url contains the word catalogue.
我希望能够检查 url 是否包含单词目录。
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?
但它不起作用。有人可以指出我哪里出错了吗?
回答by Simon
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.
indexOf 不返回真/假,它返回搜索字符串在字符串中的位置;如果未找到,则为 -1。
回答by Martin James
Seeing as the OP was already looking for a boolean result, an alternative solution could be:
鉴于 OP 已经在寻找布尔结果,替代解决方案可能是:
if (~window.location.href.indexOf("catalogue")) {
// do something
}
The tilde (~
) is a bitwise NOT operator and does the following:
波浪号 ( ~
) 是按位非运算符,执行以下操作:
~n == -(n+1)
~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.
简单来说,上面的公式将 -1 转换为 0,使其为假,其他任何值都变为非零值使其为真。因此,您可以将结果indexOf
视为布尔值。
回答by Ishan Shah
You can simply use the includes(). Kindly refer the following code.
您可以简单地使用includes()。请参考以下代码。
$(document).ready(function () {
if(window.location.href.includes('catalogue')) {
$("#trail").toggle();
}
});