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

我怎么能这样做:

<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>

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

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

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

会做到这一点。 或者,您可以使用正则表达式:

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

像这样:

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 alert("your url contains the name franky");
            }
        });
    </script>
链接地址: http://www.djcxy.com/p/75053.html

上一篇: How to check if the URL contains a given string?

下一篇: What is "~" represent in this JavaScript?