Ray*_*ess 343 javascript url jquery
我怎么能做这样的事情:
<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>
J.W*_*.W. 620
您需要添加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>Nic*_*itz 99
if (window.location.href.indexOf("franky") != -1)
会做的.或者,您可以使用正则表达式:
if (/franky/.test(window.location.href))
Sar*_*raz 25
你会这样使用indexOf:
if(window.location.href.indexOf("franky") != -1){....}
另请注意添加href字符串否则您将执行:
if(window.location.toString().indexOf("franky") != -1){....}
Adr*_*les 23
像这样:
    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 alert("your url contains the name franky");
            }
        });
    </script>
Ali*_*aru 13
window.location不是String,但它有一个toString()方法.所以你可以这样做:
(''+window.location).includes("franky")
要么
window.location.toString().includes("franky")
来自旧的Mozilla文档:
位置对象具有返回当前URL的toString方法.您还可以为window.location分配一个字符串.这意味着您可以使用window.location,就像在大多数情况下它是一个字符串一样.有时,例如,当您需要在其上调用String方法时,您必须显式调用toString.
正则表达方式:
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后面是AND :1337.
正如您所看到的,当条件变得有点棘手时,使用正则表达式优于其他解决方案.
小智 6
document.URL应该得到你URL和
if(document.URL.indexOf("searchtext") != -1) {
    //found
} else {
    //nope
} 
试试这个,它更短,完全如下window.location.href:
if (document.URL.indexOf("franky") > -1) { ... }
如果你想检查以前的网址:
if (document.referrer.indexOf("franky") > -1) { ... }
小智 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>
小智 5
如果将字符串转换为小写或大写,这将是一个很好的做法,因为 indexof() 方法区分大小写。
如果您的搜索不区分大小写,您可以简单地使用 indexOf() 方法,而无需将原始字符串转换为小写或大写:
var string= location.href;
var convertedString= string.toLowerCase();
if(convertedString.indexOf('franky') != -1)
{
    alert("url has franky");
}
else
{
    alert("url has no franky");
}
小智 5
相反,我喜欢这种方法。
top.location.pathname.includes('franky')
它在很多情况下都有效。