Skip to main content

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

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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 has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!

Latest Remote Jobs