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 ?

Answers:

Answer

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());
Answer

Regex will be your best friend here...

var filename = fullUri.replace( /^.*?([^\/]+)\..+?$/, '$1' );

Answer

Just split the string:

var src = $('img').attr('src'); // "static/images/banner/blue.jpg"
var tarr = src.split('/');      // ["static","images","banner","blue.jpg"]
var file = tarr[tarr.length-1]; // "blue.jpg"
var data = file.split('.')[0];  // "blue"
Answer
var src = $('img').attr('src').split('/');
var file = src[src.length - 1];

Should work

Answer

Say we have:

<img src="path/to/awesome/image/foobar.jpg" />

Here's what we do to extract the file name:

Array.prototype.filename = function() {
   var tmp = this.split('/');
   return tmp[tmp.length-1].match(/(.*)\.[\w]+$/)[1];
});

$('img').attr('src').filename();

Result:

console.log(name); // foobar
Answer
src = $('img').attr('src');
src_array = src.split('/');
src = src_array[src.length-1];
Answer
var src= $('img').attr('src');

var name = src.match(/static\/images\/banner\/(.*)\.jpg/)[1];

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.