我有下面的网址,所有这些网址都被认为是网站的根,我如何使用javascript location.pathname使用正则表达式来确定下面的模式,因为你会注意到“站点”这个词在这个模式中是重复的。
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对话框,只有当用户在网站的根。
发布于 2013-03-18 20:55:35
一个完整的模式,包括协议和域,可能如下所示:
/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/但是,如果您正在与location.pathname进行匹配,请尝试
/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)发布于 2013-03-18 21:05:18
只需使用DOM来解析它。不需要调用正则表达式解析器。
var url = 'http://www.somesite.tv/foobar/host/site';
urlLocation = document.createElement('a');
urlLocation.href = url;
alert(urlLocation.hostname); // alerts 'www.somesite.tv'发布于 2013-03-18 22:06:28
如果您不显式需要正则表达式来执行此操作
例如,您还可以这样做
shortest urls的递减子字符串
的
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的例子
https://stackoverflow.com/questions/15477223
复制相似问题