我有一个始终采用此格式的 URL
http://domain.tld/foo/bar/boo
http://www.domain.tld/foo/bar/boo
http://sub.domain.tld/foo/bar/boo
http://www.sub.domain.tld/foo/bar/boo
我想使用正则表达式bar从 url 中提取,无论格式如何。
我正在使用 JavaScript。
我尝试使用类似的方法来分解网址
var x = 'http://domain.tld/foo/bar/boo`'
x.split(/^((http[s]?):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/g)
Run Code Online (Sandbox Code Playgroud)
但这并没有真正起作用,也没有帮助,因为当我真的只需要值时,我似乎得到了一个数组或项目bar
var el = document.createElement('a');
el.href = "http://www.domain.tld/foo/bar/boo";
var importantPart = el.pathname.split('/')[2];
console.log(importantPart);
Run Code Online (Sandbox Code Playgroud)
小提琴: https: //jsfiddle.net/dcyo4ph5/1/
来源: https: //css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/ & JavaScript - 获取部分 URL 路径
我猜这不使用正则表达式。所以这可能不是你想要的。