kate_hudson kate_hudson - 4 months ago 12
jQuery Question

Replacing instances of string in URL

I am currently doing this

var currentImage = $('#compImg').attr('src');


This will give me one of two URLs, which are the following

http://localhost:8000/images/folder1/Yearly/somename_Yearly_something.png
http://localhost:8000/images/folder1/Monthly/somename_Monthly_something.png


The only difference is the words Monthly and Yearly. On the page that displays the image I have a select box, with the values Monthly and Yearly. If they select something, and it is not currently being displayed, I need to switch the image. So say I land on the page and it is displying the Monthly image path. If I select Monthly from the select box, nothing should happen. If I select Yearly, it should replace the URL with the Yearly URL. I think the best way to do this is just replace the occurences of Monthly in the URL to Yearly, because the rest is the same.

At the moment I have this:

$( "#yearMonth" ).change(function() {

var currentImage = $('#compImg').attr('src');

if($(this).val() == 'Yearly') {
var newImage1 = currentImage.replace("Monthly", "Yearly");
$('#dashboardImage').attr('src', newImage1 + '.png');
}

if($(this).val() == 'Monthly') {
var newImage2 = currentImage.replace("Yearly", "Monthly");
$('#dashboardImage').attr('src', newImage2 + '.png');
}
});


At the moment nothing seems to happen. How can I replace the word if needed?

Answer

The .replace function in jQuery is only replacing the first instance of the searched string.

You could use str.split(search).join(replacement) instead which replaces all of the instances. (As suggested in this thread)

You should also remove the + .png, because the url is already ending with .png.

Then the code should work and look something like this:

 $( "#yearMonth" ).change(function() {
     var currentImage = $('#compImg').attr('src');

     if($(this).val() == 'Yearly') {
         var newImage1 = currentImage.split("Monthly").join("Yearly");

         $('#dashboardImage').attr('src', newImage1);
     }

     if($(this).val() == 'Monthly') {
         var newImage2 = currentImage.split("Yearly").join("Monthly");

         $('#dashboardImage').attr('src', newImage2);
     }
 });