检查javascript中的特定url?

检查javascript中的特定url?,javascript,javascript-events,Javascript,Javascript Events,我如何在javascript中添加一些东西来检查网站上某个人的网站url,然后在找到匹配项后重定向到网站上的某个页面?例如 我们要检查的字符串将是mydirectory,因此如果有人转到mysite.com/mydirectory/anyfile.php,或者甚至mysite.com/mydirectory/index.phpjavascript会将他们的页面/url重定向到mysite.com/index.php,因为url中有mydirectory,如何使用javascript实现这一点?请

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


我们要检查的字符串将是
mydirectory
,因此如果有人转到
mysite.com/mydirectory/anyfile.php
,或者甚至
mysite.com/mydirectory/index.php
javascript会将他们的页面/url重定向到
mysite.com/index.php
,因为url中有
mydirectory
,如何使用javascript实现这一点?

请查看
窗口。尤其是位置。您可能对(部分)
pathname
属性(您可以在
/
上拆分)和
href
属性感兴趣,以更改页面


这都是假设javascript首先被提供的;因此,我假设
anyfile.php
index.php
都会导致JS被服务,而不是一些“通用404”消息。

如果我正确理解了这个问题,那么它相当简单,可以使用document.URL实现

var search = 'mydirectory'; // The string to search for in the URL.
var redirect = 'http://mysite.com/index.php' // Where we will direct users if it's found
if(document.URL.substr(search) !== -1) { // If the location of 
    // the current URL string is any other than -1 (doesn't exist)
    document.location = redirect // Redirect the user to the redirect URL.
}

使用document.URL,您可以检查URL中的任何内容,但是您可能希望在用户加载页面之前,使用类似Apache的mod_rewrite来重定向用户

在if条件中有一个额外的
=
。最好使用完全相等(==和!==)来避免(0==false)或(-1=='-1')返回true等问题。这不会影响这种情况,但也不会造成伤害。