admin管理员组

文章数量:1136516

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:

.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

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

Share Improve this question asked Aug 19, 2009 at 19:59 jim23jim23 1
  • 2 See also possible duplicate: How to get the file name from a full path using JavaScript? – Bergi Commented Oct 14, 2013 at 16:21
Add a comment  | 

16 Answers 16

Reset to default 64
var index = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(index);

Shorter way

var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
var filename = url.match(/.*\/(.*)$/)[1];
var filename= url.split('/').pop()

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:

/([^/]*?)(\.[^\./]*)?$
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).

var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1);  
alert(page);

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.

// Extract filename from current page.
var filePath = window.location.pathname;
var fileName = filePath.substr(urlPath.lastIndexOf("/") + 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

var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href)[0];

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

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)

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;

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

本文标签: How to pull the file name from a url using javascriptjqueryStack Overflow