[英]How to extract part of location.href in JavaScript?
也許不是您問題的答案,但如果您在 Javascript 中寫作,您可能想要使用 location.pathname 而不是自己從整個 href 中提取它。
既然您要求使用正則表達式解決方案,那就是:
^(?:[^:]+://)?[^/]+/([^/]+)
這匹配所有這些變體(匹配組在任何情況下都將包含"first"
):
http://www.mydomain.com/first/
http://www.mydomain.com/first
https://www.mydomain.com/first/
https://www.mydomain.com/first
www.mydomain.com/first/
(這個和下一個是為了方便)www.mydomain.com/first
為了使它成為“http://”-only,它變得更簡單:
^http://[^/]+/([^/]+)
您可以使用 window.location.host 和 window.location.search 只需查看此頁面了解詳情
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.