Tuesday, July 6, 2010

How to Get the Base Url with Javascript for a Domain or Localhost

In the code below, you will be able to find the baseUrl of your website using javascript. The following javascript code will work when used on your localhost or when it's used in a live site (finds the root url of the domain address).


function fnGetBaseURL() {
var strUrl = location.href;
// entire url including querystring - also: window.location.href;
var strBaseURL = strUrl.substring(0, strUrl.indexOf('/', 14));


if (strBaseURL.indexOf('http://localhost') != -1) {
// Base Url for localhost
var strUrl = location.href; // window.location.href;
var strPathName = location.pathname; // window.location.pathname;
var intIndex1 = strUrl.indexOf(strPathName);
var intIndex2 = strUrl.indexOf("/",intIndex1 + 1);
var strBaseLocalUrl = strUrl.substr(0, intIndex2);

return strBaseLocalUrl + "/";
}
else {
// Root Url for domain name
return strBaseURL + "/";
}

}

If you'd like to test the fnGetBaseURL function in an html page and view the result, simply add the following after the closing tag of the fnGetBaseURL () function:
document.write(fnGetBaseURL());