【问题标题】:Javascript regex to exclude all subdirectories of a given directory in a URL用于排除 URL 中给定目录的所有子目录的 Javascript 正则表达式
【发布时间】:2015-04-30 17:47:31
【问题描述】:

假设你有一个域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 控制台告诉我我的正则表达式不好。我使用* 作为通配符进行赌博,但它并没有像我希望的那样工作。

【问题讨论】:

  • 必须是正则表达式吗?为什么不window.location.pathname.indexOf('/some-directory/')
  • 使用上面的stackoverflow url,我认为这种语法对你有用:window.location.pathname.match(/^\/questions\//)(但你会使用一些目录而不是问题;)

标签: javascript regex url


【解决方案1】:

如果 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[\/]?/));

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

【讨论】:

    【解决方案2】:

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

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

    Debuggex Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多