首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从url获取第一个和最后一个文件夹

从url获取第一个和最后一个文件夹
EN

Stack Overflow用户
提问于 2020-02-12 19:27:42
回答 3查看 97关注 0票数 1

在Chrome扩展中,我有一个变量,它等于当前标签的url,比如currentUrl = tabs[0].url;。它得到一个类似于http://www.example.com/folder-1/folder-2/folder-3/index.html的url。

我想从这个url获取/folder/-1/folder-3/

我尝试了currentPath = currentUrl.substring(0, currentUrl.lastIndexOf("/"));,但是在这种方式下我只能得到完整的路径(http://www.example.com/folder1/folder2/folder3)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-02-12 19:32:43

代码语言:javascript
复制
const arr = "http://www.example.com/folder-1/folder-2/folder-3/index.html".split("/");

然后arr[3]会给你文件夹-1,arr[arr.length - 2]会给你文件夹-3

票数 2
EN

Stack Overflow用户

发布于 2020-02-12 19:32:40

要做到这一点,可能的方法之一是

代码语言:javascript
复制
splittedPath = ("http://www.example.com/folder1/folder2/folder3/index.html").split("/");
folder1 = splittedPath[3];
folderLast = splittedPath[splittedPath.length-2];
票数 1
EN

Stack Overflow用户

发布于 2020-02-12 19:55:07

让我们测试更多的案例:

代码语言:javascript
复制
function getFirstAndLastFrom( URL ){

  const a = document.createElement("a");
  a.href = URL;
  let pathname = a.pathname.split("/");
  pathname.shift();  // Filter out first entry
  pathname.pop();    // Filter out last entry
  const first = pathname.length > 0 ? pathname[0] : null; // Do we have a first element?
  const last = pathname.length > 1 ? pathname[pathname.length-1] : null; // Do we have a last element?
  return { first, last };

}
代码语言:javascript
复制
const URL1 = "http://www.example.com/folder-1/folder-2/folder-3/index.html";
const URL2 = "http://example.com/folder-1/folder-2/folder-3/";
const URL3 = "http://www.example.com";
const URL4 = "http://subdomain.example.com/folder-1/folder-2/image.jpg";
const URL5 = "http://www.example.com/folder-1/image.jpg";
const URL6 = "http://www.google.com/";

{
  // Test case #1
  let { first, last } = getFirstAndLastFrom( URL1 );
  console.log( URL1, first, last );
}

{
  // Test case #2
 let { first, last } = getFirstAndLastFrom( URL2 );
  console.log( URL2, first, last );
}

{
  // Test case #3
  let { first, last } = getFirstAndLastFrom( URL3 );
  console.log( URL3, first, last );
}

{
  // Test case #4
  let { first, last } = getFirstAndLastFrom( URL4 );
  console.log( URL4, first, last );
}

{
  // Test case #5
  let { first, last } = getFirstAndLastFrom( URL5 );
  console.log( URL5, first, last );
}

{
  // Test case #6
  let { first, last } = getFirstAndLastFrom( URL6 );
  console.log( URL6, first, last );
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60187329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档