Reputation: 18296
I want to extract filename with path and its extension separately from image's src with jquery.
for example:
<img src="images/cat/kitty.gif" id="myimg" />
I need to get "images/cat/kitty" and ".gif" from above code.
how can I do it?
Upvotes: 3
Views: 8753
Reputation: 161
If you have a complex image path that uses multiple '.' such as -
http://website.com/app/folder/imagemanager.php../../../user_images/2982034/images/image.png
Although you could clean up the path beforehand, if not, using jQuery you could try -
// Get the source
var image_src = $(el).attr('src');
// Get the extension. As mentioned above, using split() and pop()
var extension = image_src.split('.').pop();
// Get just the path. Replace the extension with ''
var path = image_src.replace('.'+extension,'');
Upvotes: 1
Reputation: 51
To extract only the file name:
var name = $('#myimg').attr("src");
var parts = name.split('/');
name = parts[parts.length-1];
Upvotes: 5
Reputation: 235962
No regex needed. Use .split()
:
var ret = $('#myimg').attr('src').split(/\./);
console.log(ret[0]); // === 'images/cat/kitty'
console.log(ret[1]); // === 'gif'
Upvotes: 4