1

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?

2 Answers 2

6

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");
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

True, easy fix: $(this).attr('src').substr(0,$(this).attr('src').length-5)+$(this).attr('src').substr(-5).replace(... etc in console substr(0,test.length-5) + test.substr(-5).replace('a.jpg','c.jpg').replace('b.jpg','c.jpg') works as expected

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.