2

I'm sure this is something simple, but I can't figure it out.

I have this HTML:

<img src="/7290/9200572193_f95fb66c50_m.jpg" />

Which I need to change to

<img src="/7290/9200572193_f95fb66c50_b.jpg" />

This isn't always the same image, but the _m.jpg and _b.jpg are. How can I do this with jQuery?

JacobTheDev
  • 17,318
  • 25
  • 95
  • 158
  • Are you just trying to replace "_m.jpg" by "_b.jpg" in a string or what ? If so it's a very simple use case for [replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace). – Denys Séguret Jul 03 '13 at 19:34
  • Yes. I need to do this for multiple images, too, if that matters. I think I can figure that out, though, I just need help changing the `_m` to `_b`. – JacobTheDev Jul 03 '13 at 19:36

4 Answers4

2

You can do:

var imgSrc = "/7290/9200572193_f95fb66c50_m.jpg";
imgSrc = imgSrc.replace("_m.jpg", "_b.jpg");
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

Something like this may help you:

$( "img" ).each(function() {
  var src = $( this ).attr( "src" );
  $( this ).attr( "src", src.replace( /_m\.(.*)$/, "_b.$1" ) );
});

This will not depend on the extension of your src attribute.

gustavohenke
  • 40,997
  • 14
  • 121
  • 129
1

Loop through "img" tags with $("img").each(function(){ doStuff(); });. Change attributes with attr("attribute","new_value"), get attributes with attr("attribute"). Replace with replace("from","to").

$("img").each(function(){
  $(this).attr("src",$(this).attr("src").replace("_m","_b"));
});
Samuel Reid
  • 1,756
  • 12
  • 22
0

In short, use.replace. Such as:

"/7290/9200572193_f95fb66c50_m.jpg".replace('_m.jpg', '_b.jpg');
/*  OR  */
var url = "/7290/9200572193_f95fb66c50_m.jpg";
url.replace('_m.jpg', '_b.jpg');

You use .each() in jQuery to loop through a group of elements. Thus you can use a simple selector like $('img') to select all images on the view and then make changes in the callback method. You would then use .prop to both set and get the current src and change it using old fashioned .replace

$("img").each(function(i) {
    $(this).prop("src", $(this).prop("src").replace('_m.jpg', '_b.jpg'));
});

Example

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • `prop` should be used for boolean values I believe, `attr` would be used to replace a source. – tymeJV Jul 03 '13 at 19:37
  • @tymeJV no, prop will work. prop changes how booleans are tested, but still reads "properties" of an element as much as `attr` – SpYk3HH Jul 03 '13 at 19:42
  • @tymeJV [Pretty good explanation here](http://stackoverflow.com/questions/5874652/prop-vs-attr) – SpYk3HH Jul 03 '13 at 19:45