Friday, April 10, 2009

JavaScript: Get the Current URI's Domain Name

We have consultants that do some work for us (who doesn't?). I have a beta site setup for them to test with. But for some reason when I check the beta site, the URI's for this one part are going directly to the production site. "Hmmm...why...oh huh?! why!?" So it turns out they were hard-coding a domain root as part of the URI in one of their javascript runs. Now really, what kind of portability does that give me!?

Their code looked similar to this:var uri = 'http://drincruz.blogspot.com/' + uriPath;

So, I figured I'll fix this little nuisance by writing a quick function that will get the domain root of a URI. Now, I'm sure there's some sort of built-in function that'll get me what I need, but I couldn't find it. So if there is, someone please let me know!


function getDomainRoot()
{
var uri = location.href;
var startIndex;
if (null != uri.match("file:///") )
startIndex = 8;
if (null != uri.match("http://") )
startIndex = 7;
if (null != uri.match("https://") )
startIndex = 8;
var endIndex = uri.indexOf("/", startIndex);
var domainRoot = uri.substring(0, endIndex);
return domainRoot;
}


Now, I can put this function into their javascript and it can now be used like this:
var uri = getDomainRoot + '/' + uriPath;

/* I should really add a trailing slash check. Ah well. Next time! */

Cheers!

No comments: