用斜杠分割 Url 并按顺序重新组合它们(角度、打字稿)

问题描述 投票:0回答:1

我正在尝试创建面包屑导航,但在创建父 URL 时陷入困境。

所以我的想法是:

  1. 从子级别获取完整的 URL

  2. 用斜杠分割该 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']
angular typescript breadcrumbs
1个回答
0
投票

您可以在 URL 路径分隔符 pathname

 上拆分 URL 的 
/
,然后迭代路径部分来构建列表:

TS游乐场

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")));

© www.soinside.com 2019 - 2024. All rights reserved.