Search code examples
jqueryreplaceimagewildcardsrc

jQuery wildcard character in image source


I would like to change the src attribute of an image on click using jQuery. Here's the HTML:

<a href="#" class="view2">View 2</a>
<img src="images/shoe1a.jpg" class="sb-player" />

And in the img src, I want to replace the "a" to a "b," but my problem is that I want to ignore the "1" that's in front of it, since it could look like this as well:

<img src="images/shoe2a.jpg" class="sb-player" />

I got this far with my jQuery, and the asterisk is where I need a wildcard character:

$(function() {
    $('.view2').click(function() {
        $('.sb-player').attr('src', 'images/shoe'+*+'b.jpg');
        return false;
    });
});

Is there a certain character that could be a wildcard for any number?


Solution

  • Just .replace() the entire end of the src string, replacing a.jpg with b.jpg.

    You can pass a function to .attr().

    The parameter i represents the current iteration in the set, and val is the current value. The return value represents the new value.

    $(function() {
        $('.view2').click(function() {
            $('.sb-player').attr('src', function(i,val) { 
                 return val.replace('a.jpg','b.jpg');
            });
            return false;
        });
    });