Robert Pessagno
Robert Pessagno

Reputation: 529

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?

Upvotes: 2

Views: 1784

Answers (2)

Luca
Luca

Reputation: 1100

The most powerful way to match any part of a string is using Regular Expressions in javascript.

Maybe in this way you can solve your problem:


$(function() {
    $('.view2').click(function() {
        var originalSrc = $('.sb-player').attr('src');
        $('.sb-player').attr('src', originalSrc.replace(/a\./,"b."));
        return false;
    });
});

Upvotes: 1

user113716
user113716

Reputation: 322492

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;
    });
});

Upvotes: 3

Related Questions