JavaScript
Article

Update images with a specific src (relative path) with absolute path

By Sam Deering

jQuery code snippet to update images with a domain name, turning it from a relative path into an absolute path. Sometimes useful when testing across domains with the same static content or pulling images from an external domain.

replace-url-absolutw

(function ($) {
    $(document).ready(function () {
        $('img').each(function (i, v) {
            var $el = $(this),
                s = $el.attr('src'),
                sRx = /[/res/images/.*]+/igm;
            console.log(s);
console.log(s.test(sRx));
            if (s.test(sRx)) {
                console.log('match');
                s = 'http://splash.abc.net.au' + s;
                $el.attr('src', s);
            }
        });
    });
})(jQuery);

jsfiddle.net/BK9Zp/

JSfiddly lolz.

There is an awesome project by Ben Alman which has all the bells and whistles in this area check it out:
https://raw.github.com/cowboy/jquery-urlinternal/master/jquery.ba-urlinternal.js

Sam Deering
Meet the author
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.