1

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!

1

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

You could get the last subdirectory like so

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

4 Comments

You might also add add .split("?")[0] on the return statement to remove parameters
I'm not sure for me the last subdirectory is "HPNAVTILES" so there is no "?" after I guess
This worked great Jimmy - thanks so much!
I'm glad this help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.