Patrioticcow
Patrioticcow

Reputation: 27058

jQuery - How to check if img src lacks filename?

I have a <img>:

 <img src="http://example.com/mmm/01.jpg" class="test">

How can I check if the src is missing the 01.jpg and replace it with some other image?

Basically

if (img src is 'http://example.com/mmm/') { 
    replace src with 'http://example.com/mmm/test.jpg'
}

Upvotes: 0

Views: 4241

Answers (6)

Phrogz
Phrogz

Reputation: 303321

// Can 'fix' many imgs at once (with the appropriate logic in the body)
$('img').attr('src',function(i,src){
  // If it's a JPG, leave it alone, otherwise...
  return /jpe?g$/.test(src) ? src : 'http://example.com/mmm/test.jpg';
});

Upvotes: 0

Liv
Liv

Reputation: 6124

$(yourImg).attr("src") will return you (or allow you to set) the url for the image as a string so you can then compare it with the values mentioned above.

Upvotes: 0

Fabien
Fabien

Reputation: 105

Check $("img.test").attr("src")

Upvotes: 0

Ryan
Ryan

Reputation: 6866

You can check the last character in the src attribute to see if it's a '/' or not...

var img = $("img.test");
var src = $(img).attr("src");

if (src.lastIndexOf("/")+1 == src.length){
    $(img).attr("src",src+"test.jpg");
}

Upvotes: 1

DarthJDG
DarthJDG

Reputation: 16591

Solution: jQuery/JavaScript to replace broken images

This is the first hit not just on stack overflow, but on google as well...

Upvotes: 2

Vivin Paliath
Vivin Paliath

Reputation: 95558

Something like this should work:

var $img = jQuery("#myImg");
var src = $img.attr("src");

// if you have more image types, just add them to the regex. 
// I've used png and jpg as examples
if(!/\.(jpg|png)$/.test(src)) {

   var img = "test.jpg";

   // to see if the src url ends with / or not
   if(!/\/$/.test(src)) {
      img = "/" + img;
   }

   $img.attr("src", src + img);
}

Upvotes: 3

Related Questions