Replace Extensions of Images from .jpg to .png using jQuery

A recent requirement demanded that all the .jpg images on a page be replaced with .png’s. Here’s how to solve this requirement using jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Change Image Extensions</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<script type="text/javascript">
$(function() {
$("#replAll").click(function() {
$('img').each(function() {
var src = $(this).attr("src");
$(this).attr("src", src.replace(/\.jpg$/i, ".png"));
});
});
});
</script>
</
head>
<
body>
<
input id="replAll" type="button" value="Replace" /><br />
<
img src="images/abc.jpg" />
<
img src="images/emo.jpg" />
</
body>
</
html>

OUTPUT

jQuery change extensions

Clicking on the ‘Replace’ button changes all .jpg’s to their .png’s counterpart. I have used different images to be able to demonstrate that the images did get changed.

jQuery change extensions



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

WD.acgrs said...

A better way to write it would be:

$(function() {
$("#replAll").click(function() {
$('img').attr("src", function(i, attr) {
return attr.replace(/\.jpg$/i, ".png");
});
});
});