0

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'
}
Johnny Bones
  • 8,557
  • 6
  • 41
  • 108
Patrioticcow
  • 25,174
  • 72
  • 208
  • 332

6 Answers6

3

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);
}
Vivin Paliath
  • 91,149
  • 38
  • 215
  • 293
2

Solution: jQuery/JavaScript to replace broken images

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

Community
  • 1
  • 1
DarthJDG
  • 16,331
  • 11
  • 48
  • 55
  • +1. In that post, this comment is the best solution in my opinion: http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images/#comments-168448 – Levi Morrison Apr 21 '11 at 16:46
1

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");
}
Ryan
  • 6,688
  • 12
  • 47
  • 68
0

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

kapa
  • 75,446
  • 20
  • 155
  • 173
Fabien
  • 105
  • 9
0

$(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.

kapa
  • 75,446
  • 20
  • 155
  • 173
Liv
  • 5,926
  • 1
  • 21
  • 29
0
// 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';
});
Johnny Bones
  • 8,557
  • 6
  • 41
  • 108
Phrogz
  • 284,740
  • 104
  • 634
  • 722