我正在尝试创建面包屑导航,但在创建父 URL 时陷入困境。
所以我的想法是:
从子级别获取完整的 URL
用斜杠分割该 URL 并按顺序重新组合它们
那么简单,如果 URL 是:
www.nice.com/events/registration/form
然后,点赞:
www.nice.com/events/registration/form
www.nice.com/events/registration
www.nice.com/events
www.nice.com
然后反转顺序并推入数组,如下所示:
['www.nice.com', 'www.nice.com/events', 'www.nice.com/events/registration', 'www.nice.com/events/registration/form']
您可以在 URL 路径分隔符 pathname
上拆分 URL 的
/
,然后迭代路径部分来构建列表:
function createPaths(url: URL): URL[] {
const paths: URL[] = [];
const pathParts = url.pathname.split("/");
for (let i = 0; i < pathParts.length; i += 1) {
paths.push(new URL(pathParts.slice(0, i + 1).join("/"), url.origin));
}
// Possibly desired: If the input URL has query or fragment data,
// add a final URL to the list which includes that data:
if (url.search || url.hash) {
const finalUrl = new URL(paths.at(-1)!);
finalUrl.search = url.search;
finalUrl.hash = url.hash;
paths.push(finalUrl);
}
return paths;
}
const url = new URL("https://www.nice.com/events/registration/form");
const paths = createPaths(url);
console.log(paths); // ["https://www.nice.com/","https://www.nice.com/events","https://www.nice.com/events/registration","https://www.nice.com/events/registration/form"]
console.log(createPaths(new URL("https://www.nice.com/events/registration/form?key=value#footer"))); // ["https://www.nice.com/","https://www.nice.com/events","https://www.nice.com/events/registration","https://www.nice.com/events/registration/form","https://www.nice.com/events/registration/form?key=value#footer"]
从 Playground 编译 JS:
function createPaths(url) {
const paths = [];
const pathParts = url.pathname.split("/");
for (let i = 0; i < pathParts.length; i += 1) {
paths.push(new URL(pathParts.slice(0, i + 1).join("/"), url.origin));
}
if (url.search || url.hash) {
const finalUrl = new URL(paths.at(-1));
finalUrl.search = url.search;
finalUrl.hash = url.hash;
paths.push(finalUrl);
}
return paths;
}
const url = new URL("https://www.nice.com/events/registration/form");
const paths = createPaths(url);
console.log(paths);
console.log(createPaths(new URL("https://www.nice.com/events/registration/form?key=value#footer")));