Javascript 如何使用jQuery获取图像名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8807877/
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-24 07:36:26  来源:igfitidea点击:

How to get an image name using jQuery?

javascriptjquery

提问by lepix

Let's says I have :

假设我有:

<img src='static/images/banner/blue.jpg' />

Using jQuery, how could I get the bluedata ?

使用 jQuery,我如何获取blue数据?

If I use $('img').attr('src'), I can get the whole URI. In that case, what is the best way to remove the extension and all the path ?

如果我使用$('img').attr('src'),我可以获得整个 URI。在这种情况下,删除扩展名和所有路径的最佳方法是什么?

回答by kennebec

There are a couple gotcha here- local files may use the other slash ('\') in the pathname, and some filenames can have hash or search tails defined, or not have an extension.

这里有几个问题 - 本地文件可能在路径名中使用另一个斜杠 ('\'),并且某些文件名可以定义散列或搜索尾部,或者没有扩展名。

String.prototype.filename=function(extension){
    var s= this.replace(/\/g, '/');
    s= s.substring(s.lastIndexOf('/')+ 1);
    return extension? s.replace(/[?#].+$/, ''): s.split('.')[0];
}

console.log($('img').attr('src').filename());

回答by KOGI

Regex will be your best friend here...

正则表达式将是您最好的朋友...

var filename = fullUri.replace( /^.*?([^\/]+)\..+?$/, '$1' );

var filename = fullUri.replace( /^.*?([^\/]+)\..+?$/, '$1' );

回答by Blazemonger

Just split the string:

只需拆分字符串:

var src = $('img').attr('src'); // "static/images/banner/blue.jpg"
var tarr = src.split('/');      // ["static","images","banner","blue.jpg"]
var file = tarr[tarr.length-1]; // "blue.jpg"
var data = file.split('.')[0];  // "blue"

回答by Rob

var src = $('img').attr('src').split('/');
var file = src[src.length - 1];

Should work

应该管用

回答by daryl

Say we have:

假设我们有:

<img src="path/to/awesome/image/foobar.jpg" />

Here's what we do to extract the file name:

这是我们提取文件名的操作:

Array.prototype.filename = function() {
   var tmp = this.split('/');
   return tmp[tmp.length-1].match(/(.*)\.[\w]+$/)[1];
});

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

Result:

结果:

console.log(name); // foobar

回答by Dau

src = $('img').attr('src');
src_array = src.split('/');
src = src_array[src.length-1];

回答by PeeHaa

var src= $('img').attr('src');

var name = src.match(/static\/images\/banner\/(.*)\.jpg/)[1];