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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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");
});
});
});