Reputation: 18520
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?
Upvotes: 2
Views: 103
Reputation: 22570
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'));
});
Upvotes: 0
Reputation: 1756
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"));
});
Upvotes: 1
Reputation: 41440
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.
Upvotes: 1
Reputation: 104775
You can do:
var imgSrc = "/7290/9200572193_f95fb66c50_m.jpg";
imgSrc = imgSrc.replace("_m.jpg", "_b.jpg");
Upvotes: 2