How to pull the file name from a url using javascript/jquery?
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
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:
/([^/]*?)(\.[^\./]*)?$