0

I want to look through the entire page on a site and replace relative img paths with "/". For example:

    $("body img").attr("src",function(){
        return this.src.replace("uploads","/uploads");
    });

However, in cases where the relative path could be different than whats above, I want to use regex to account for all the different scenarios. I know the images will all reside in the same location, but the various paths to replace could be "uploads, ../uploads, or ../../uploads, etc.

Any help would be appreciated..?

3
  • I believe some browsers report the absolute URL of the image src, instead of what's in the HTML attribute. This will complicate things. Regardless, what's the value of what you're trying to do? Are you changing the actual images? Commented Nov 8, 2012 at 4:23
  • ...or simplify things. You could check first up if the URL is already absolute, and then set the attribute explicitly to that. Or I suppose for all intents and purposes, your work there is done. Of course you still have to handle the case where the browser does NOT do this for you. Commented Nov 8, 2012 at 4:25
  • Thats a good point. I did not think of browsers who change links. Im actually requesting this for a cms that automatically changes links as a cleanup mechanism (go figure). So my ultimate goal is to find all paths that are not /uploads/... and change them accordingly. Im not replacing images, just ensuring that once cms editing is complete, the images will still work. Commented Nov 8, 2012 at 5:12

1 Answer 1

1

use this

$('img').each(function(){
    $(this).attr('src',$(this).attr('src').replace(/^/,"/"));
      $('body').append('<br />');
$('body').append($(this).attr('src'));

})​

here is fiddle

http://jsfiddle.net/7yNg7/

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

2 Comments

Thanks, but this does not account for "../" or "../../" How would i account for those with regex as they are more common
Had to do some minor tweaks but finally got it working the way i needed. Just had to change .replace(/^/,"/")); to .replace(/.*uploads/,"/my/jmg/path")); Thanks for the help.

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.