我怎么能这样做呢:

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

当前回答

窗口位置是一个包含多个方法和道具的对象,其中一些是与URL相关的字符串,这样你就可以安全地搜索目标字符串:

const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"

// another option 
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"

// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true

位置对象

其他回答

这是我的代码♥

function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
    return true;
}
else {
    console.log("Error", "The link is not valid");
}
return false;}
if (window.location.href.indexOf("franky") != -1)

会这么做的。或者,你可以使用regexp:

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

放入你的js文件

                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');
                }

你可以像这样使用indexOf:

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

还要注意字符串的href,否则你会这样做:

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

试试这个:

<script type="text/javascript">             
    $(document).ready
    (
        function () 
        { 
            var regExp = /franky/g;
            var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
            if(regExp.test(testString)) // This doesn't work, any suggestions.                 
            {                      
                alert("your url contains the name franky");                 
            }             
        }
    );         
</script>