views:

1005

answers:

8

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

A: 

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
Nope. That results in a match of `["http:"]`.
Crescent Fresh
+2  A: 

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
+6  A: 
var index = yourstring.lastIndexOf("/");
var filename = yourstring.substr(index);
Gregoire
is this faster than using a regex?
I don't know but more understandable by a human
Gregoire
a LOT faster.Indeed, there is a typo in the code. The method must be substr instead of substring, as the parameters of the substring method are mandatory, while substr has 1 mandatory (start) and 1 optional (length)
Rodrigo
Thanks for the correction Rodrigo
Gregoire
@Rodrigo: The second parameter of `substring()` is optional as well. If omitted, it extracts to the end of the string. References: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring and Section 15.5.4.15 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
Grant Wagner
I'm getting `/filename.gif` instead of `filename.gif`. The index should be incremented by 1 before calling substr.
Protron
A: 

Shorter way

var filename = window.location.href.substr(window.location.href.lastIndexOf("/"));
Rodrigo
+1  A: 
var filename = url.match(/.*\/(.*)$/)[1];
CMS
A: 
// Extract filename from current page.
var filePath = window.location.pathname;
var fileName = filePath.substr(urlPath.lastIndexOf("/") + 1);
Sam Deng
A: 

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
A: 
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