Regular expression in jquery to get image file name

I want to extract the file name with a path and its extension separately from the src image using jquery.

eg:

<img src="images/cat/kitty.gif" id="myimg" />

I need to get "images / cat / kitty" and ".gif" from the code above.

How can i do this?

+3
source share
4 answers

Instead, you can use attr:

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

If you want to specify the name and extension separately, you can do:

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

To extract only the file name:

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

. .split():

var ret = $('#myimg').attr('src').split(/\./);

console.log(ret[0]);  // === 'images/cat/kitty'
console.log(ret[1]);  // === 'gif'
+4

, '.' -

http://website.com/app/folder/imagemanager.php../../../user_images/2982034/images/image.png

, , jQuery, -

// 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,'');
+1
source

Source: https://habr.com/ru/post/1794073/


All Articles