I am retrieving few images from an API and changing them to my own images as follows:
$('img[src="http://www.example.com/dir/images/dir/1.gif"]').attr('src', "http://cdn.example.com/dir/1.gif");
$('img[src="http://www.example.com/dir/images/dir/2.gif"]').attr('src', "http://cdn.example.com/dir/2.gif");
$('img[src="http://www.example.com/dir/images/dir/3.gif"]').attr('src', "http://cdn.example.com/dir/3.gif");
$('img[src="http://www.example.com/dir/images/dir/4.gif"]').attr('src', "http://cdn.example.com/dir/4.gif");
$('img[src="http://www.example.com/dir/images/dir/5.gif"]').attr('src', "http://cdn.example.com/dir/5.gif");
$('img[src="http://www.example.com/dir/images/dir/6.gif"]').attr('src', "http://cdn.example.com/dir/6.gif");
$('img[src="http://www.example.com/dir/images/dir/7.gif"]').attr('src', "http://cdn.example.com/dir/7.gif");
$('img[src="http://www.example.com/dir/images/dir/8.gif"]').attr('src', "http://cdn.example.com/dir/8.gif");
$('img[src="http://www.example.com/dir/images/dir/9.gif"]').attr('src', "http://cdn.example.com/dir/9.gif");
$('img[src="http://www.example.com/dir/images/dir/10.gif"]').attr('src', "http://cdn.example.com/dir/10.gif")
Now, because there’s way too much text I compressed this as follows:
$('img[src^="http://www.example.com/"]').each(function(index,element){
var $this, src, newSrc;
$this = $(this);
src = $this.attr('src');
newSrc = src.replace('www.example.com/dir/images/dir', 'cdn.example.com/dir');
$this.attr('src', newSrc);
});
Now, I want to change my images extension to .png. So basically I want to replace the URL for each images AND the extension from .gif to .png.
How can I achieve this?
1 Answer