idontwantnoscrubs idontwantnoscrubs - 1 year ago 67
jQuery Question

Change ending of img src to render a different scene7 image preset. (regex help)

I am trying to change the ending of our image src's in order to render images smaller on mobile. We use Adobe Scene 7, so I can set presets for a full size image, and then a mobile image and then I just need code to make the url change. I found this question on here and am trying to apply it to my code. My problem is that I have no idea how to write a regular expression for this, the dollar signs are throwing me off.

$('img').each(function () {
var src = $(this).attr('src');
$(this).attr('src', src.replace($fullbanner$, '$mobilebanner$');

So to make it simple, could someone help me write a regular expression that would fill in the "src.replace( , );" section? The initial value of the url would be domain/company/banners/homepage/img_name?$fullbanner$ and then we just need it to change to domain/company/banners/homepage/img_name?$mobilebanner$.

Also, if it's as easy as just saying:

src.replace('$fullbanner$', '$mobilebanner');

then just say so. I really appreciate any help that is offered.

Answer Source

You can use attr(function) which will loop over each instance:

$('img').attr('src', function(index, existingSrc){
    return existingSrc.replace('$fullbanner$', '$mobilebanner');

Note that this isn't a very effective strategy as it won't prevent the browser making the initial requests for the full size images since any images that exist in initial page load will already have requests made before your script runs