Amar Amar - 6 months ago 31
jQuery Question

Jquery to find an replace text after last slash in an image src url

I know the question i've posted here is quit silly but after hours of googling and trying all most everything i could not get the desired result. So let me share it here in a hope to get solved here.

My problem is, i've an Image url source where i need to change Image name with new image name everytime.
I'll post my tried code:

$(function () {
//Old Image Url where i need to change 32_Penguins.jpg with new file name
var ImageSrcUrl="../Upload\UserProfile\32_Penguins.jpg";
var NewFileName="Tullips.jpg";

//I tried to replace everything after the last "\"[slash]
ImageSrcUrl= ImageSrcUrl.replace(/.*$/i, NewFileName);

alert(ImageSrcUrl);
});

Answer

$(function () {
     //Old Image Url where i need to change 32_Penguins.jpg with new file name
     var ImageSrcUrl="../Upload/UserProfile/32_Penguins.jpg";     
     var index = ImageSrcUrl.lastIndexOf("/") + 1;
     var path = ImageSrcUrl.substr(0,index);
     var NewFileName="Tullips.jpg";
     ImageSrcUrl= path+NewFileName; 
     alert(ImageSrcUrl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>