【发布时间】:2009-03-09 16:29:36
【问题描述】:
在这个例子中,从 location.href 中提取 'first' 的正则表达式是什么,例如:
【问题讨论】:
标签: javascript regex
在这个例子中,从 location.href 中提取 'first' 的正则表达式是什么,例如:
【问题讨论】:
标签: javascript regex
也许不是您问题的答案,但如果您使用 Javascript 编写,您可能希望使用 location.pathname 而不是自己从整个 href 中提取它。
【讨论】:
【讨论】:
既然你要求一个正则表达式解决方案,那就是它:
^(?:[^:]+://)?[^/]+/([^/]+)
这匹配所有这些变体(匹配组 1 在任何情况下都将包含 "first"):
http://www.mydomain.com/first/http://www.mydomain.com/firsthttps://www.mydomain.com/first/https://www.mydomain.com/firstwww.mydomain.com/first/(这个和下一个是为了方便)www.mydomain.com/first为了使它成为“http://”-only,它变得更简单了:
^http://[^/]+/([^/]+)
【讨论】:
您可以使用 window.location.host 和 window.location.search 详情请查看this page
【讨论】:
var re = /^http:\/\/(www.)?mydomain\.com\/([^\/]*)\//;
var url = "http://mydomain.com/first/";
if(re.test(url)) {
var matches = url.match(re);
return matches[2]; // 0 contains whole URL, 1 contains optional "www", 2 contains last group
}
【讨论】: