Javascript 正则表达式排除 URL 中给定目录的所有子目录

Javascript regex to exclude all subdirectories of a given directory in a URL

假设您有一个域http://www.somedomainname.com

所有页面上的代码应该 运行 除了 some-directory 中更深的内容:http://www.somedomainname.com/some-directory/anything

我试过:

(function($) {

    $(document).ready(function() {

        var isBad = !!window.location.pathname.match(/^\/some-directory/*);
        if ( !isBad ) {

            // RUN CODE
        }

    });

}(jQuery));

并且 Chrome 控制台告诉我我的正则表达式有问题。我使用 * 作为通配符进行赌博,但结果并不如我所愿。

这个简单的 Debuggex 正则表达式怎么样?

^\/some-directory\/[\s\S]

Debuggex Demo

如果 some-directory 始终是路径名中的第一件事,您实际上并不需要通配符,但您应该处理可能丢失的尾部斜杠(通常提供 index.html 之类的文件):

var testing = "";
console.log(testing = "/some-directory", testing.match(/^\/some-directory[\/]?/));
console.log(testing = "/some-directory/", testing.match(/^\/some-directory[\/]?/));
console.log(testing = "/some-directory/something", testing.match(/^\/some-directory[\/]?/));
console.log(testing = "/wont-find/some-directory", testing.match(/^\/some-directory[\/]?/));

如果您需要在路径中的任何位置找到该目录名称,您可以在开头添加通配符:

var testing = "";
console.log(testing = "/some-other-dir/some-directory", testing.match(/^.*\/some-directory[\/]?/));
console.log(testing = "/some-other-dir/some-directory/", testing.match(/^.*\/some-directory[\/]?/));
console.log(testing = "/some-other-dir/some-directory/something", testing.match(/^.*\/some-directory[\/]?/));

然而,这两个示例都需要前导斜杠。