Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an image name using jQuery?

Let's says I have :

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

Using jQuery, how could I get the blue data ?

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 ?

like image 737
lepix Avatar asked Jan 10 '12 17:01

lepix


2 Answers

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());
like image 178
kennebec Avatar answered Oct 23 '22 07:10

kennebec


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

Should work

like image 40
Rob Avatar answered Oct 23 '22 06:10

Rob