Javascript:如何检查URL中是否包含某个词

11

我想检查浏览器中的URL是否包含单词“Desktop”(我从桌面启动了HTML文件)。它的URL是:"file:///C:/Users/Joe/Desktop/TestAlert.html"

但是,应该出现警报,但这不起作用。

这是我的代码:

<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.contains("Desktop") > -1) {
       alert("Alert: Desktop!");
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

我在Firefox, Chrome和Internet Explorer中测试过这个。 如果有人能帮忙,那会非常好!


你是在寻找“查询字符串”参数还是从“URL”中获取任何字符串? - Rayon
1
请使用indexOf代替contains。 - Pradeep Potnuru
7个回答

34

该方法是String.prototype.indexOf()

if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
}

而且您不需要为此使用DOM Ready。


谢谢,这真的很有帮助!“DOM准备就绪。”那就是重点。 - Joe SharePoint

3
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

请尝试这个方法,它会给您解决方案。


2

您可以使用正则表达式

url = window.location.href;
if( url.match(/desktop/gi) ) {
   alert("Alert: Desktop!");
}

你可以使用这个功能来检查两个或更多单词,比如“/desktop|home/gi”


1
请使用 indexOf 代替。
console.log(window.location.href.indexOf("javascript"));

同样的规则适用,任何 > -1 的内容都意味着它已经找到了某些东西。


1
如果你想使用jQuery,你需要链接到它的源代码。此外,使用indexOf而不是contains
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("Desktop") > -1) {
       alert("Alert: Desktop!");
    } else {
        alert("window.location.href: " + window.location.href);
    }
});
</script>
</head>
<body>
    <h1>Test001</h1>
</body>
</html>

提示:当您遇到JavaScript问题时,请在浏览器中按F12打开开发工具,然后按F5刷新页面。然后检查控制台选项卡以获取错误消息,例如“未捕获的引用错误:$未定义”,并检查源选项卡以查找任何被红色下划线标记的代码部分。

0
如果(window.location.href.indexOf("在此输入您想查找的单词") > -1) { alert("该单词已存在!"); }
完全按照您的要求工作!!

您的回答可以通过添加更多支持性信息来改进。请[编辑]以添加更多细节,例如引用或文档,以便他人确认您的答案是否正确。您可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0
var url = window.location.href;
            console.log(url);
            console.log(~url.indexOf("#product-consulation"));
            if (~url.indexOf("#product-consulation")) {
                console.log('YES');
                // $('html, body').animate({
                //     scrollTop: $('#header').offset().top - 80
                // }, 1000);
            } else {
                console.log('NOPE');
            }

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