使用 JavaScript 从路径中获取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2526061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:45:35  来源:igfitidea点击:

Getting just the filename from a path with JavaScript

javascriptjqueryhtmlpath

提问by DCD

I have a full path to an image, which I am using jQuery to read like this:

我有一个图像的完整路径,我使用 jQuery 来读取它:

$('img.my_image').attr('src');

However I just want the filenameportion (i.e. without full path).

但是我只想要文件名部分(即没有完整路径)。

Are there any built-in functions to do this, or would a regexbe the only option?

是否有任何内置函数可以做到这一点,或者正则表达式是唯一的选择?

回答by rash

var Filename= path.split('/').pop()

回答by Gregtheitroade

var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);

回答by Ali Habibzadeh

function getFileName(path) {
return path.match(/[-_\w]+[.][\w]+$/i)[0];
}

回答by RubbelDeCatc

I found a better version handling unix and windows-like path-strings.

我找到了一个更好的版本来处理 unix 和类似 windows 的路径字符串。

Number 1:

1号:

var unix_path = '/tmp/images/cat.jpg';
console.log(unix_path.replace(/^.*[\\/]/, ''));

var win_path = 'c:\temp\images\cat.jpg';
console.log(win_path.replace(/^.*[\\/]/, ''));

Output will be cat.jpg

输出将是cat.jpg

Number 2: (maybe faster)

2号:(也许更快)

var unix_path = '/tmp/images/cat.jpg';
console.log(unix_path.split(/[\\/]/).pop());

var win_path = 'c:\temp\images\cat.jpg';
console.log(win_path.split(/[\\/]/).pop());

Output will be cat.jpg

输出将是cat.jpg

回答by Robusto

In Javascript you could do

在 Javascript 你可以做

function getFileNameFromPath(path) {
  var ary = path.split("/");
  return ary[ary.length - 1];
}

回答by The Bad Brad

Using this solution you can get both names i.e. with and without file extension.

使用此解决方案,您可以获得两个名称,即带有和不带有文件扩展名。

    //getting image source
    var path=$('img.my_image').attr('src');

    //splitting url and getting filename with file extension
    var file=path.split('/').pop();

    //removing extension and keeping just the filename
    var filename=file.split('.').shift();