March 15, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Replace Extensions of Images from .jpg to .png using jQuery"
  1. WD.acgrs said...
    March 15, 2010 10:53 AM

    A better way to write it would be:

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

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions