0

I want to get the image name and its extension of a some images with jquery. I use split method.it is ok in firefox but i IE it get the full address of image with domain name so it has some (.)s before getting the (.) of image extension.

is there a better way to do that? here is the code i use:

 var imagename = $("img",this).attr("src").split(".")[0];
 var  imageextension = $("img",this).attr("src").split(".")[1];

thanks.

hd.
  • 17,596
  • 46
  • 115
  • 165
  • possible duplicate of [How to pull the file name from a url using javascript/jquery?](http://stackoverflow.com/questions/1302306/how-to-pull-the-file-name-from-a-url-using-javascript-jquery) – Jakub Konecki Mar 02 '11 at 10:40

2 Answers2

2
// get the last path fragment
var lastFragment = $('img', this).attr('src').match(/\/([^\/]+)$/)[1];
// split dot fragments
var lastFragmentSplit = lastFragment.split('.');
// name is first
var imageName = lastFragmentSplit[0];
// extension is second
var imageExtension = lastFragmentSplit[1];

Note: this simple solution won't work as you expect if you have filenames like names.with.dots.then.extension.jpg.

The reason why it doesn't work as you expect in IE is because IE resolves the full, absolute URI when you ask for the src even if the original attribute you supply has only a file name. Firefox leaves it intact.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
0

Your code is quite in-efficient. You are querying all the img objects twice. Try:

$('img').each(function(index) {
    var parts = this.attr( 'src' ).split( '.' );
    console.log( parts );
});
Fokko Driesprong
  • 2,075
  • 19
  • 31
  • I think that the problem is that $("img",this).attr("src") is a collection (all the img's of the page). The split() method doens not apply on a collection.. – Fokko Driesprong Mar 02 '11 at 10:42
  • No, it's because the OP wants to exclude the protocol, domain and path, and only split and use the last fragment. Your answer does basically the same thing as OP's initial code. – Delan Azabani Mar 02 '11 at 10:45