Получить первую и последнюю папку из URL - PullRequest
0 голосов
/ 12 февраля 2020

В расширении Chrome у меня есть переменная, равная URL текущей вкладки, например currentUrl = tabs[0].url;. Он получает URL-адрес типа http://www.example.com/folder-1/folder-2/folder-3/index.html.

Я хочу получить /folder/-1 и /folder-3/ из этого URL-адреса.

Tried currentPath = currentUrl.substring(0, currentUrl.lastIndexOf("/"));, но на этом пути я получаю только целое путь (http://www.example.com/folder1/folder2/folder3)

Ответы [ 3 ]

2 голосов
/ 12 февраля 2020
const arr = "http://www.example.com/folder-1/folder-2/folder-3/index.html".split("/");

Тогда arr[3] даст вам папку-1, а arr[arr.length - 2] даст вам папку-3

1 голос
/ 12 февраля 2020

Давайте проверим еще несколько случаев:

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 };

}

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 голос
/ 12 февраля 2020

Один из возможных способов сделать это

splittedPath = ("http://www.example.com/folder1/folder2/folder3/index.html").split("/");
folder1 = splittedPath[3];
folderLast = splittedPath[splittedPath.length-2];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...