Home > other >  How to extract last directory and file name from URL in javascript?
How to extract last directory and file name from URL in javascript?

Time:11-06

I need to extract the last subdirectory and the file name from an image like this (the subdirectory name is not consistent and the position of the ):

example.com/dw/image/v2/BFKH_PRD/on/demandware.static/-/Library-Sites-RefArchSharedLibrary/default/dw981dad25/Homepage/2021/11_NOV/1102/HPNAVTILES/1102_WGA_NAV_TILES_01_01.jpg?sw=40&q=100

I am using this js to pull out the file name, which works great, but I have no idea how to get the last subdirectory.

function() {
  var url = {{INSERT URL}};
  return url.substr(url.lastIndexOf('/') 1).split('?')[0];
}

Thanks a bunch!

CodePudding user response:

If your URL is guaranteed to be valid—and start with a protocol—I would try and do as little parsing myself as possible. Here's one solution:

url = 'https://example.com/dw/image/v2/BFKH_PRD/on/demandware.static/-/Library-Sites-RefArchSharedLibrary/default/dw981dad25/Homepage/2021/11_NOV/1102/HPNAVTILES/1102_WGA_NAV_TILES_01_01.jpg?sw=40&q=100';

const lastDirectory = (url) => {
  const parsed = new URL(url);
  const path = parsed.pathname.split('/');
  return path.slice(-2).join('/');
};

console.log(lastDirectory(url));

By using JavaScript's URL(), we do not have to deal with removing the query string (or other parts of URLs) ourselves: we can easily extract the path and perform our operations on it.

Output:

HPNAVTILES/1102_WGA_NAV_TILES_01_01.jpg

CodePudding user response:

You could get the last subdirectory like so

  function() {
      var url = {{INSERT URL}};
      directories = url.split("/")
      lastSubdirectory = directories[directories.length - 2]
      return lastSubdirectory
    }
  • Related