How to Get the Base Url with Javascript for a Domain or Localhost
by
Doug
Updated August 25, 2014
Here's a script example to get the base url (root domain) using Javascript. This will get the localhost baseurl or the root url of a domain name.
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).
Just add this javascript function to a .js file or script tag :
function getBaseURL() {
var url = location.href; // entire url including querystring - also: window.location.href;
var baseURL = url.substring(0, url.indexOf('/', 14));
if (baseURL.indexOf('http://localhost') != -1) {
// Base Url for localhost
var url = location.href; // window.location.href;
var pathname = location.pathname; // window.location.pathname;
var index1 = url.indexOf(pathname);
var index2 = url.indexOf("/", index1 + 1);
var baseLocalUrl = url.substr(0, index2);
return baseLocalUrl + "/";
}
else {
// Root Url for domain name
return baseURL + "/";
}
}
If you'd like to test the getBaseURL function in an html page and view the result, simply add the following after the closing tag of the getBaseUrl() function:
document.write(getBaseURL());
Here's an example of the code above placed in an html page: Figure 1