How to catch the end filename only from a path with javascript?
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
A regular expression replace would work, barring any special function to do this:
var filename = path.replace(/.*\//, '');
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 */
精彩评论