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,786
  • 7
  • 52
  • 117
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

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
  • 94,126
  • 40
  • 223
  • 295
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,511
  • 11
  • 49
  • 56
  • +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,756
  • 13
  • 49
  • 68
0

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

kapa
  • 77,694
  • 21
  • 158
  • 175
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
  • 77,694
  • 21
  • 158
  • 175
Liv
  • 6,006
  • 1
  • 22
  • 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,786
  • 7
  • 52
  • 117
Phrogz
  • 296,393
  • 112
  • 651
  • 745