在JavaScript中检查某些URL

Check certain URL in JavaScript?

本文关键字:URL 检查 JavaScript      更新时间:2023-09-26

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

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

如果我正确理解了这个问题,那么它相当简单,可以使用文档实现。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.
}

使用文档。URL你可以检查URL中的任何内容,但你可能想在用户加载页面之前,使用Apache的mod_rewrite之类的东西来重定向用户。

查看window.location,特别是它的属性和方法。您可能对pathname属性(的一部分)感兴趣(您可以在/上拆分它),并对href属性感兴趣以更改页面。

这一切都是假设javascript首先被提供;所以我假设anyfile.phpindex.php都会导致JS被服务,而不是一些"通用404"消息。