hd.
hd.

Reputation: 18296

regular expression in jquery to get image filename

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

Answers (4)

milesholt
milesholt

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

Anurag Dutta
Anurag Dutta

Reputation: 51

To extract only the file name:

    var name = $('#myimg').attr("src");
    var parts = name.split('/');
    name = parts[parts.length-1];

Upvotes: 5

jAndy
jAndy

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

Sarfraz
Sarfraz

Reputation: 382646

You can simply use attr method instead:

$('#image_id').attr('src');

If you want name and extension separately, you can do:

var arr = $('#image_id').attr('src').split('.');
alert(arr[0]);    // name
alert(arr[1]);    // extension

Upvotes: 5

Related Questions