1

I am trying to change the string within an attr('src') in just the beginning of the address, and after the replacement, it keeps the latter information. Here's the html:

<img src="../folder1/folder2/folder3/picture.png" />

<img src="../folder1/folder2/folder3/picture2.png" />

It would need to perform this after pageload, here's my existing script/scripts:

$(document).ready(function(e) {
    // this is one attempt
    $('img').each(function() {
        var src = $(this).attr('src');
        $(this).ready(function() {
            $(this).attr('src', src.replace('../', '/'));
        }, function() {
            $(this).attr('src', src);
        });
    });

    // this is another attempt, not both used at the same time
    $('img').attr('src').replace('../', '/');

    // I also tried this
    $('img').each(function() {
        if($(this).attr('src') == '../') {
            $(this).attr('src', '/');
        };
    });
});

The overall goal is to produce this result:

<img src="/folder1/folder2/folder3/picture.png" />

<img src="/folder1/folder2/folder3/picture2.png" />
1
  • this.src, don't need the extra jquery objects Commented Jan 22, 2016 at 20:51

1 Answer 1

4

You have to get the current src - update it, then re-assign it:

$('img').attr('src', function(index, src) {
    return src.replace('../', '/')
})
Sign up to request clarification or add additional context in comments.

1 Comment

my data server went down, your solution works in a small jsfiddle, I'll flag as answer as soon as I can test on the server :)

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.