0

If I have a variable 'path' which contains a full path with directories and all, to the filename, how can I strip everything except the filename?

ex: Convert dir/picture/images/help/filename.jpg into filename.jpg

Thanks

2 Answers2

4

A regular expression replace would work, barring any special function to do this:

var filename = path.replace(/.*\//, '');
Jeff B
  • 29,943
  • 7
  • 61
  • 90
2

Whatever you use, consider whether the string may have a GET string or a hash tail, and if a file name may not have an extension.

String.prototype.filename= function(){
   var s= this.substring(this.lastIndexOf('/')+1);
   var f=  /^(([^\.\?#]+)(\.\w+)?)/.exec(s);
   return f[1] || '';
}
var url= 'http://www.localhost.com/library/paul_1.html?addSrc=5';
alert(url.filename()) /*  returns>> paul_1.html */
kennebec
  • 102,654
  • 32
  • 106
  • 127