Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
How to extract last directory and file name from URL in javascript?

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!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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
about 4 years ago · Juan Pablo Isaza Denunciar

0

You could get the last subdirectory like so

  function() {
      var url = {{INSERT URL}};
      directories = url.split("/")
      lastSubdirectory = directories[directories.length - 2]
      return lastSubdirectory
    }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda