40

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

1

16 Answers 16

63
var index = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(index);
Sign up to request clarification or add additional context in comments.

7 Comments

is this faster than using a regex?
I'm getting /filename.gif instead of filename.gif. The index should be incremented by 1 before calling substr.
Use slice instead of substr: JavaScript: Slice, Substring, or Substr?
@Gregoire What happens if the / is a \ how do you get the file name then?
@Pomster var index = yourstring.lastIndexOf("\\") + 1;
|
27

Shorter way

var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);

2 Comments

This does not support filename.php/arctile/slug-name (it will return slug-name)
I would recommend using document.URL in place of window.location.href when you're only retrieving the value.
13
var filename = url.match(/.*\/(.*)$/)[1];

Comments

12
var filename= url.split('/').pop()

Comments

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:

/([^/]*?)(\.[^\./]*)?$

1 Comment

I find this regex clearer, but it is not written in JavaScript... Here's the full thing: url.match('[^/]*$')[0]
4
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).

2 Comments

Great, but can you expand the functionality of also cutting away the parameters in the end, including a "?" ? Thanks
@JamesCazzetta: maybe overkill for your needs, but this will get you everything you need from a URI: gist.github.com/1169555
3
var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1);  
alert(page);

Comments

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.

Comments

2
// Extract filename from current page.
var filePath = window.location.pathname;
var fileName = filePath.substr(urlPath.lastIndexOf("/") + 1);

1 Comment

what is urlPath? It's not variable or a window property.
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

1 Comment

Nope. That results in a match of ["http:"].
1
var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href)[0];

Comments

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

1 Comment

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)
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.

Comments

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)

Comments

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;

Comments

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

Comments

Your Answer

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