39

A certain variable might contain a relative path or an absolute path. Either way, I need to be able to pull the filename from the variable:

http://www.somesite.com/dir1/dir2/filename.gif
/dir1/dir2/filename.gif

The directory structure is also arbitrary. So basically given either of the url's above (with arbirtrary directory structure) I need to pull 'filename.gif'. Thanks in advance

  • 2
    See also possible duplicate: [How to get the file name from a full path using JavaScript?](http://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript) – Bergi Oct 14 '13 at 16:21

16 Answers16

64
var index = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(index);
Travis
  • 12,001
  • 8
  • 39
  • 52
Gregoire
  • 24,219
  • 6
  • 46
  • 73
  • is this faster than using a regex? –  Aug 19 '09 at 20:08
  • 2
    I'm getting `/filename.gif` instead of `filename.gif`. The index should be incremented by 1 before calling substr. – Mariano Desanze Oct 21 '10 at 20:19
  • 1
    Use `slice` instead of `substr`: [JavaScript: Slice, Substring, or Substr?](http://www.jacklmoore.com/notes/substring-substr-slice-javascript/) – Web_Designer May 15 '13 at 18:58
  • @Gregoire What happens if the / is a \ how do you get the file name then? – Pomster Mar 11 '14 at 08:56
  • 1
    @Pomster var index = yourstring.lastIndexOf("\\") + 1; – Gregoire Mar 11 '14 at 13:44
  • Thank you for not using a regex. – RayLoveless Jun 04 '14 at 15:17
  • this doesn't handle the edge case where URL contains a nested encoded URL. You could end up with a value like this `?url=https%3A%2F%2Ffoobar%2Fimage.jpg` when you actually wanted `image.jpg`. I posted my [answer that handles this case](https://stackoverflow.com/a/68264052/8234457) – Caleb Taylor Jul 06 '21 at 03:21
27

Shorter way

var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
Rodrigo
  • 4,365
  • 3
  • 31
  • 49
  • 1
    This does not support filename.php/arctile/slug-name (it will return slug-name) – TroodoN-Mike Dec 20 '12 at 20:46
  • I would recommend using [`document.URL`](https://developer.mozilla.org/en-US/docs/Web/API/document.URL?redirectlocale=en-US&redirectslug=DOM%2Fdocument.URL) in place of `window.location.href` when you're only retrieving the value. – Web_Designer May 15 '13 at 19:01
13
var filename = url.match(/.*\/(.*)$/)[1];
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
11
var filename= url.split('/').pop()
rash
  • 1,316
  • 1
  • 12
  • 17
6

I'd use a regular expression.

[^/]*$

It selects everything after the last slash until the end. You can expand it to select the extension separately:

/([^/]*?)(\.[^\./]*)?$
Thom Smith
  • 13,916
  • 6
  • 45
  • 91
  • 1
    I find this regex clearer, but it is not written in JavaScript... Here's the full thing: `url.match('[^/]*$')[0]` – Jason Apr 19 '14 at 01:22
5
var path = window.location.pathname;
var filename = path.match(/.*\/([^/]+)\.([^?]+)/i)[1];

Use this in the case that you don't want your query string to be part of your filename (which you probably don't).

kflorence
  • 2,187
  • 2
  • 16
  • 15
  • Great, but can you expand the functionality of also cutting away the parameters in the end, including a "**?**" ? Thanks – James Cazzetta Oct 05 '12 at 07:25
  • 1
    @JamesCazzetta: maybe overkill for your needs, but this will get you everything you need from a URI: https://gist.github.com/1169555 – kflorence Oct 09 '12 at 23:41
3
var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1);  
alert(page);
afro360
  • 620
  • 3
  • 9
  • 22
2
// Extract filename from current page.
var filePath = window.location.pathname;
var fileName = filePath.substr(urlPath.lastIndexOf("/") + 1);
Sam Deng
  • 21
  • 2
2

For your examples, substring searching will probably be your best option.

However, if your URIs are actually complex enough, you might try Steven Levithan's parseUri:

parseUri(uri).file;

It has 2 modes and each has its share of quirks, so be sure to check out the demo.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

thanks sam deng, seems to work but you have a typo my friend:

// Extract filename from current page.
var filePath = window.location.pathname;
var fileName = filePath.substr(filePath.lastIndexOf("/") + 1);
dwaves.de
  • 11
  • 1
  • thanks for your help, but you should leave this as a comment to the relative answer rather than posting a new one (in future you will be able to suggest an edit to others' answers) – Luca Oct 19 '12 at 21:36
1

Use a regular expression, something along these lines should do the trick:

[^/]+\.[^/]+

Although that doesn't cover every possible case, it should be more than suitable for most cases. You can these use:

var url = window.location.href;
var regex = new RegExp("[^/]+\.[^/]+");
var fileName = regex.exec(url);

Hope that helps

LorenVS
  • 12,597
  • 10
  • 47
  • 54
1
    var pathnameArray = window.location.pathname.split("/");
    var nameOfFile = pathnameArray[pathnameArray.length -1];

There's probably some overhead I don't know about when considering making an array versus using the substr others have mentioned. So maybe this isn't a great answer but rather a different approach to solving the same problem.

ross studtman
  • 936
  • 1
  • 8
  • 22
1

I solved this problem by this:

var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1); 
// then display your filename to console
console.info(page)
1
var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href)[0];
0

If you url is like this:

yourdomain.com/app_dev.php
yourdomain.com/app_dev.php/article/2

and you want to just pull filename (/app_dev.php) so that you can link to your homepage use this:

var filename = window.location.pathname.substr(0, window.location.pathname.indexOf("/", 1));
window.location = filename;
TroodoN-Mike
  • 15,687
  • 15
  • 55
  • 78
0

My answer handles edge case where the URL is encoded or the URL contains a query value that's an encoded URL, where the / becomes %2F.

const getImageNameFromURL = (urlInput) => {
  const imageFullnameResult = urlInput.match(/.+(\/|%2F)(.+)/);

  if (!imageFullnameResult) return null;

  const imageFullname = imageFullnameResult[2];

  const imageNameResult = imageFullname.match(
    /.+(jpg|png|svg|jpeg|webp|bmp|gif)/
  );

  if (!imageNameResult) return imageFullname;

  const imageName = imageNameResult[0];

  if (!imageName) return null;

  return imageName;
};

// common URL
const commonURL = 'https://static.tvtropes.org/pmwiki/pub/images/aubrey_plaza.jpg?quality=75&w=1200&h=900&crop=1'

// URL contains query which is an encoded URL which is the actual image.
const urlContainsEncodedURL = 'https://ca-times.brightspotcdn.com/dims4/default/a7ccc15/2147483647/strip/true/crop/2048x1152+0+0/resize/840x473!/quality/90/?url=https%3A%2F%2Fcalifornia-times-brightspot.s3.amazonaws.com%2Fd5%2Fb5%2Fa8bffb00214d8bd8149373c18a6a%2Fla-1467703026-snap-photo'

console.log(getImageNameFromURL(commonURL))
// result: aubrey_plaza.jpg


console.log(getImageNameFromURL(urlContainsEncodedURL))
// result: la-1467703026-snap-photo
Caleb Taylor
  • 2,670
  • 2
  • 21
  • 31