newbie
newbie

Reputation: 14950

Jquery replace using regex

I want to replace my images that ends with a.jpg and b.jpg with c.jpg.

My code is as follows:

$(".test").each(function() {            
    var src = $(this).attr("src"){
    if(src.match(/a.jpg$/)){
        src.replace("a.jpg", "c.jpg");
    } else if (src.match(/b.jpg$/)){
        src.replace("b.jpg", "c.jpg");
    }
    $(this).attr("src", src);       
});

but it is complicated.. how can i do this using regex?

Upvotes: 1

Views: 2547

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Since you'r only replacing the end of the src attribute, and the extention is included, it's safe to say there will be only one occurrence of the (a|b).jpg substring. In other words $(this).attr('src').replace('a.jpg','c.jpg').replace('b.jpg','c.jpg') will do exactly the same as Tatu's answer, without regular expressions.

Please, please, please to anyone who reads this: when manipulating strings, don't turn to regex by default, think twice. Probably 85% of regex-related questions on SO are cases where an alternative, regex-less (and in most cases better) solution is possible.

Upvotes: 1

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124758

You don't need check if the pattern matches, just do the replace:

$(".test").each(function() {
    $(this).attr("src", $(this).attr('src').replace(/[ab]\.jpg$/, "c.jpg");
});

Upvotes: 6

Related Questions