0

如果找到匹配项,我如何在 javascript 中添加一些内容来检查网站上某人的网站 url,然后重定向到网站上的某个页面?例如...

我们要检查的字符串将是 mydirectory,所以如果有人去mysite.com/mydirectory/anyfile.php甚至mysite.com/mydirectory/index.php,javascript 会将他们的页面/url 重定向到,mysite.com/index.php因为它在 url 中有 mydirectory,否则如果找不到匹配项,请不要重定向,我'正在使用下面的代码...

var search2 = 'mydirectory';
var redirect2 = 'http://mysite.com/index.php'

if (document.URL.substr(search2) !== -1)
    document.location = redirect2

问题在于,即使没有找到匹配项,它总是为我重定向,有谁知道出了什么问题,有没有更快/更好的方法来做到这一点?

4

2 回答 2

2

改用String.indexOf()

if (window.location.pathname.indexOf('searchTerm') !== -1) {
    // a match was found, redirect to your new url
    window.location.href = newUrl;
}
于 2012-04-11T03:08:47.447 回答
0

substr在这种情况下不是您需要的,它从字符串中提取子字符串。而是使用indexOf

if(window.location.pathname.indexOf(search2) !== -1) {
    window.location = redirect2;
}

如果可能,最好在服务器端执行此重定向。它将始终有效,对搜索引擎更加友好且速度更快。如果您的用户禁用了 JavaScript,他们将不会被重定向。

于 2012-04-11T03:08:07.243 回答