如何检查URL是否包含给定的字符串?

475

我该如何做类似这样的事情:

<script type="text/javascript">
$(document).ready(function () {
    if(window.location.contains("franky")) // This doesn't work, any suggestions?
    {
         alert("your url contains the name franky");
    }
});
</script>

4
"window.location.contains is not a function" - gene b.
21个回答

839

您需要添加 href 属性并检查 indexOf 而不是 contains

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    if (window.location.href.indexOf("franky") > -1) {
      alert("your url contains the name franky");
    }
  });
</script>


3
我有一个像这样的长URL:http://preview.tbwabox.co.nz/_v005/index.html#buying-a-car,我想检查字符串中是否包含“buying-a-car”,但脚本不起作用? - Vennsoh
8
你无法找到“买车”是因为你需要查找 window.location.hash 而不是 window.location.href。只需在 OP 的函数中交换这些值即可。 - Adrian Gonzales
2
@J.W. 为什么不能使用>0,而要使用>-1 - Elshan
5
因为严格来讲,如果 .href 以 "franky" 开头, .href.indexOf("franky") 可能会返回一个值为 0。当然,在这种情况下,它永远不会这样做,因为 .href 总是以协议,通常为 "http:" 或 "file:" 开头。尽管如此,在与 indexOf() 的结果进行比较时,您应该始终使用 >-1、>=0 或者我的首选方式 !==-1。 - robinCTS
如果您的搜索不区分大小写,请将字符串转换为小写或大写,因为indexof()方法是区分大小写的。这样做将是一个很好的实践。 - GeniusGeek
显示剩余2条评论

130
if (window.location.href.indexOf("franky") != -1)

你可以这样做。或者,你可以使用正则表达式:

if (/franky/.test(window.location.href))

5
两个选项的利弊比较是这个答案的一个不错的补充。 - Chris
1
但如果我使用正则表达式,没有人能够读懂它 ;) - RayLoveless
const url = new URL(window.location.href); const path = url.pathname; if (/^/test($|/|-)/.test(path)) { //做些什么 }这是方法 - guruguldmand

37
你可以这样使用indexOf
if(window.location.href.indexOf("franky") != -1){....}

还要注意添加href字符串,否则你会执行以下操作:

if(window.location.toString().indexOf("franky") != -1){....}

32

window.location并不是一个字符串,但它有一个toString()方法。因此你可以像这样操作:

(''+window.location).includes("franky")
或者
window.location.toString().includes("franky")

来自旧版Mozilla文档

位置对象有一个toString方法,返回当前的URL。您也可以将字符串分配给window.location。这意味着在大多数情况下,您可以像处理字符串一样使用window.location。但有时(例如需要调用一个字符串方法时),您必须明确调用toString。


4
在Firefox 48中,String.prototype.contains()已被移除。请仅使用String.prototype.includes()。请点击此处查看 - CaseyC
@CaseyC 已更新。感谢! - Alin Purcaru

25

像这样:

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 alert("your url contains the name franky");
            }
        });
    </script>

调用window.location.indexOf和window.location.href.indexOf有什么区别? - starsplusplus
@starsplusplus 没有任何区别。window.location.hrefwindow.location的别名 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/location - Adrian Gonzales
上述代码对我来说运行良好,但是对于两个变量,如何检查它们是否包含了这两个值? - Vinoth Narayan
1
@VinothNarayan 您可以在 if 语句中简单地添加另一个条件。为了确保两个条件都满足,您可以使用 Javascript 中的 AND 运算符,即 &&if( window.location.href.indexOf("cart") > -1 && window.location.href.indexOf("box") > -1 )要检查它是否具有其中一个值,请使用 OR 运算符,即两个竖线字符 ||if( window.location.href.indexOf("cart") > -1 || window.location.href.indexOf("box") > -1 ) - Adrian Gonzales

12

正则表达式方法:

var matches = !!location.href.match(/franky/); //a boolean value now

或者简单地说,您可以使用以下语句:

if (location.href.match(/franky/)) {

我使用这个来测试网站是在本地运行还是在服务器上运行:

location.href.match(/(192.168|localhost).*:1337/)

这个检查函数会判断 href 是否包含 192.168 或者 localhost,并且后面跟着 :1337

从上面可以看出,在条件比较棘手的情况下,使用正则表达式比其他解决方案更具有优势。


不错。我使用了 if (window.parent.location.href.match(/?/)) { window.parent.location = window.parent.location.pathname; },它运行得非常好... - Tarik
如果我不需要使用匹配项,那么对我来说使用 if(/franky/.test(location.href)) { /* regex matched */ } 更加简洁。 - cchamberlain
是的,在这种情况下,test肯定比match更清晰。 - Stephan Bijzitter

7

document.URL可以获取到当前页面的URL

if(document.URL.indexOf("searchtext") != -1) {
    //found
} else {
    //nope
} 

6

试试这个,它更短,并且与window.location.href完全相同:

if (document.URL.indexOf("franky") > -1) { ... }

另外,如果您想检查以前的URL:

if (document.referrer.indexOf("franky") > -1) { ... }

@sixstarpro 我没有进行负评,但是,也许很明显的原因是你给出了与18个月前发布的这个答案相同的答案!此外,关于document.referrer的额外信息与问题完全无关。 - robinCTS

5
我更喜欢这种方法。
top.location.pathname.includes('franky')

在许多情况下它都能正常工作。


5
更易上手
<script type="text/javascript">
$(document).ready(function () {
    var url = window.location.href;
    if(url.includes('franky'))    //includes() method determines whether a string contains specified string.
    {
         alert("url contains franky");
    }
});
</script>

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