首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于确定网站根目录的正则表达式

用于确定网站根目录的正则表达式
EN

Stack Overflow用户
提问于 2013-03-18 20:47:37
回答 3查看 475关注 0票数 0

我有下面的网址,所有这些网址都被认为是网站的根,我如何使用javascript location.pathname使用正则表达式来确定下面的模式,因为你会注意到“站点”这个词在这个模式中是重复的。

代码语言:javascript
复制
 http://www.somehost.tv/sitedev/
 http://www.somehost.tv/sitetest/
 http://www.somehost.tv/site/

 http://www.somehost.tv/sitedev/index.html
 http://www.somehost.tv/sitetest/index.html
 http://www.somehost.tv/site/index.html

我试图只显示jQuery对话框,只有当用户在网站的根。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-03-18 20:55:35

一个完整的模式,包括协议和域,可能如下所示:

代码语言:javascript
复制
/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/

但是,如果您正在与location.pathname进行匹配,请尝试

代码语言:javascript
复制
/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)
票数 0
EN

Stack Overflow用户

发布于 2013-03-18 21:05:18

只需使用DOM来解析它。不需要调用正则表达式解析器。

代码语言:javascript
复制
var url = 'http://www.somesite.tv/foobar/host/site';
    urlLocation = document.createElement('a');

urlLocation.href = url;
alert(urlLocation.hostname);    // alerts 'www.somesite.tv'
票数 2
EN

Stack Overflow用户

发布于 2013-03-18 22:06:28

如果您不显式需要正则表达式来执行此操作

例如,您还可以这样做

  • 使用您的urls填充数组
  • 循环遍历

    shortest urls的递减子字符串

  • 将其与最长element.

  • 进行比较

  • ,直到它们匹配。

代码语言:javascript
复制
 var urls = ["http://www.somehost.tv/sitedev/",
 "http://www.somehost.tv/sitetest/",
 "http://www.somehost.tv/site/",
 "http://www.somehost.tv/sitedev/index.html",
 "http://www.somehost.tv/sitetest/index.html",
 "http://www.somehost.tv/site/index.html"]

     function getRepeatedSub(arr) {
         var srt = arr.concat().sort();
         var a = srt[0];
         var b = srt.pop();
         var s = a.length;
         while (!~b.indexOf(a.substr(0, s))) {
             s--
         };
         return a.substr(0, s);
     }
 console.log(getRepeatedSub(urls)); //http://www.somehost.tv/site   

这里有一个关于JSBin的例子

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15477223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档