Arman Ospanov
Arman Ospanov

Reputation: 143

Use regex to change img src

I want to change image source according to a letter button that I click on. I guess that I need to use regular expression, but I am not sure how exactly it should look like.

<img id="logo_layer2" src="images/logo/logo_compass_a_layer2_red.png">
<ul id="letters">
    <li>A</li>
    <li>B</li>
    <li>C</li>
...
</ul>

"a_layer2" part should change to "b_layer2", "e_layer2" and so on.

events: {
    "click #letters li" : "change_letter"
},

change_letter: function(e) {
    var letter = $(e.target).text();       
    var newimg = /images\/logo\/logo_\w*_\w{1}_layer\d_\w*.png/.replace((/\w{1}/,letter));
    $("#logo_layer2").attr("src",newimg);
},

http://jsfiddle.net/uLqBY/

Upvotes: 1

Views: 135

Answers (2)

Vasili Syrakis
Vasili Syrakis

Reputation: 9641

To improve on the regex, you can utilise positive lookbehind and lookaheads as follows:

(?<=images\/logo\/logo_\w*_)\w{1}(?=_layer\d_\w*.png)

This will match simply the letter that you intend to change, in this case it is the 'a' in the src.

As for the jquery/js, I don't know.

Upvotes: 0

Try

fiddle Demo

$('#letters li').click(function(){
    var txt =$(this).text().toLowerCase();
    $('#logo_layer2').attr('src',function(_,old_src){
        return old_src.replace(/_\w_/g,'_'+txt+'_');
    });
});


fiddle Demo

$('#letters li').click(function(){
    var txt =$(this).text().toLowerCase();
    $('#logo_layer2').prop('src',function(_,old_src){
        return old_src.replace(/_\w_/g,'_'+txt+'_');
    });
});

.prop()

Read .prop() vs .attr()

Upvotes: 1

Related Questions