Search code examples
javascriptjqueryreplacehrefattr

JavaScript .replace() part of a url not working


running into a little issue, can't quite figure it out. I'm using jQuery on a page to handle some image loading and lightboxing. Part of the feature set requires replacing a portion of an anchor tags href to direct it towards a different resource.

there are a variable amount of images in the set, so I'm using jQuery's .each() method to grab them, replace part of the url, then fade them in one after the order. The fading works correctly, but JavaScript's .replace() isn't taking effect (though if i turn them into a variable and log it i see the correct results) and if i chain the fade in function to the back of .replace it doesn't get executed.

feels like the value isn't being returned to the elements. what am i missing?

thanks for your help!

HTML:

<a class="test" href="aresourcewithextension_b.jpg">
    <img src="aresourcewithextension_a.jpg" />
</a>

JavaScript:

$('.test').each(function(i){
    $(this).attr('href').replace('_b.jpg','_c.jpg').delay(100*i).animate({opacity:1},200);
});

Solution

  • You need to set the replaced href. .replace itself won't update the original string.

    Try like below,

    this.href = this.href.replace('_b.jpg','_c.jpg');