views:

1537

answers:

3

I'm currently using the following function to 'convert' a relative URL to an absolute one:

function qualifyURL(url) {
 var a = document.createElement('a');
 a.href = url;
 return a.href;
}

This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').

The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute - the problem with this is that it generates a server request; something I want to avoid.

So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?


Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!

There must be a way to do it without having to create a mammoth of a regex'y solution??

A: 

If url does not begin with '/'

Take the current page's url, chop off everything past the last '/'; then append the relative url.

Else if url begins with '/'

Take the current page's url and chop off everything to the right of the single '/'; then append the url.

Else if url starts with # or ?

Take the current page's url and simply append url


Hope it works for you

geowa4
You forgot that URLs can begin with "//", which makes them scheme-relative. //foo.com/bar/
Scott Wolchok
+2  A: 

You could use js-uri to resolve the relative URI to an absolute one.

Gumbo
Thank you Gumbo, I suppose this'll have to do. I would've liked a more concise solution but thank you anyway, I never knew this js-uri class existed!
J-P
+4  A: 

How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.

function escapeHTML(s) {
    return s.split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
}
function qualifyURL(url) {
    var el= document.createElement('div');
    el.innerHTML= '<a href="'+escapeHTML(url)+'">x</a>';
    return el.firstChild.href;
}

A bit ugly, but more concise than Doing It Yourself.

bobince
Awesome, thanks bobince!
J-P
This method works great for me! Thanks for posting it!
zachleat