1

How can I replace URL address of an image source string only before the name of file?

Right now I am doing this like a hard coded way as $('img').attr('src', add+"slide1.jpg"); but I need to get rid of the name of file in the JS part and just update the URL string before the name of files

var add = "https://lamaisonduchien.ca/wp-content/uploads/revslider/home_1/";
$(".button").on("click", function(){
     $('img').attr('src', add+"slide1.jpg");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Update</button><br />
<img src="http://www.dpwts.com/slide1.jpg" alt="Smiley face" height="300" width="300">
<img src="http://www.aseanta.org/images/slide/slide1.jpg" alt="Smiley face" height="300" width="300">

1 Answer 1

1

What you could do is use a regex to check for jpg or gif etc...:

^.+(?=.*\b.+\.(jpg|gif))

  • from the beginning of the string ^
  • take one or more characters .+
  • use a positive lookahead to check if the string ends on .jpg or .gif
    • match a word boundary \b
    • take one or more characters .+
    • match a dot \.
    • followed by the extension jpg or gif

var add = "https://lamaisonduchien.ca/wp-content/uploads/revslider/home_1/";
$(".button").on("click", function(){
    $('img').each(function(index, val) {
        var src = $(val).attr("src");
        var pattern = /^.+(?=.*\b.+\.jpg)/;
        $(val).attr("src", src.replace(pattern, add));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Update</button><br />
<img src="http://www.dpwts.com/slide1.jpg" alt="Smiley face" height="300" width="300">
<img src="http://www.aseanta.org/images/slide/slide1.jpg" alt="Smiley face" height="300" width="300">

Then you could use replace to replace the matches value with your add variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.