I’ve been experimenting with different methods of retrieving a qualified (absolute) URL from a relative one. To show you what I mean let’s assume we have an anchor with the href attribute set to ‘page.html':

<a href="page.html">Page</a>

How do we get the fully qualified URL which this href represents (e.g. ‘http://www.whatever-domain.com/path/to/page.html‘)?

The method below works quite well in most browsers but unfortunately (and unsurprisingly) it fails in IE6:

alert( theAnchor.href );
// All 'compliant' browsers return the fully qualified URL! :D
// IE6 returns just 'page.html' :(

Of course, you could go the complicated route and do something like this, but why make something so complicated when it doesn’t need to be? I think you’ll agree that regardless of how ‘hacky’ my method is it’s a lot better than a near 40 line string/regex marathon!

My magical method:

function qualifyURL(url){
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified url
    img.src = null; // no server request
    return url;
// Tested successfully in IE6/7, FF2/3, Safari3, Opera9, Chrome (All on Windows XP)
var myRelativeURL = 'blah/page.html';
alert( qualifyURL(myRelativeURL) );

Oddly, IE6 returns a fully qualified URL for images (src) but does not do so for anchors (href). If you look at the above function you’ll notice that the generated image’s src is set to null; this is not entirely necessary but prevents any server requests after the new image is created.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!