Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBaseURL() javascript call function in a href=""

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

like image 943
meohmy Avatar asked May 30 '11 19:05

meohmy


1 Answers

function getBaseURL () {
   return location.protocol + "//" + location.hostname + 
      (location.port && ":" + location.port) + "/";
}

Edit: Addressed Mike Samuel's point on nonstandard ports.

like image 159
Cristian Sanchez Avatar answered Oct 03 '22 05:10

Cristian Sanchez