I am calling the based url through javascript in a html page and I want to add the base url to call a link
eg.
<a href="getBaseURL()/filepath/index.html">Page</a>
The javascript is as follows:
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 + "/";
}
}
EDIT
Its just to get any base URL from the domain in question. Also, I got this code from a tutorial so any suggestions that will require less processing would be great thanks
SECOND EDIT
Hi All thanks for your answers so far, however, I am looking to call the function to the html tag as in <a href="getURL()/filepath/file.html></a>. This is where the problem lies, I am unsure how to do that
localhost0andlocalhost.foo.comare perfectly valid domains and not ones that are typically treated specially in /etc/hosts or other name resolution configurations, so your"http://localhost" === baseUrl.substring(0, 14)has an awful lot of hidden assumptions. You are also ignoring the effect of a<base href=>.baseURLcould be than? I have the feeling you do a lot of unnecessary processing...