Change end of filename using jQuery


I am currently trying to change the number at the end of a image path on click.

$(".container-button").click(function(){
    $("img.picture").each(
            function(){
                var p = $(this).attr('src');
                var new_image = p.replace('3.jpg' || '2.jpg' || '1.jpg', '4.jpg');
                $(this).attr('src',new_image);
            }
        );
});

If you take a look at my code I do the following:

  • on click i search the class for the image source and store it in a variable
  • I create a new variable that looks for the end of the image file for a set of filenames, replaces it with 4.jpg, and stores it in a variable new_image.
  • I look for the source attribute and switch it for what is stored in new_image.

What im seeing is that it only looks to replace if it finds the first filename in the set but the others are ignored.

what am I doing wrong?

The OR condition will stop after evaluating the first string '3.jpg' and will ignore the others.

To use OR in regex, you can use | operator. So, (1|2|3)\.jpg can be used. However, character class is bit fast and range can be used in it.

$(".container-button").click(function() {
    $("img.picture").attr('src', function(i, value) {
        return value.replace(/[1-3]\.jpg$/i, '4.jpg');
    });
});

Other than that, attr() can be used with callback function to change the src attribute of all the matched elements.

The RegEx /[1-3]\.jpg$/i will match

  1. A number between 1 and 3
  2. Followed by . character(This need to escape to match literal)
  3. Followed by jpg at the end of the string.
  4. The i flag is used to match the string case-in-sensitively.