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
function getBaseURL () {
return location.protocol + "//" + location.hostname +
(location.port && ":" + location.port) + "/";
}
Edit: Addressed Mike Samuel's point on nonstandard ports.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With