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'
}

6 Answers 6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Solution: jQuery/JavaScript to replace broken images

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

1 Comment

+1. In that post, this comment is the best solution in my opinion: stackoverflow.com/questions/92720/…
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");
}

1 Comment

This may not always work. What if he doesn't have a trailing / and no image? Like http://www.google.com ?
0

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

Comments

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.

Comments

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';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.