In joomla php there I can use $this->baseurl
to get the base path, but I wanted to get the base path in jquery.
The base path may be any of the follo
This is an extremely old question, but here are the approaches I personally use ...
As many have already stated, this works for most situations.
var url = window.location.origin;
However, this simple approach can be used to strip off any port numbers.
var url = "http://" + location.host.split(":")[0];
Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...
var url = window.location.protocol + "//" + location.host.split(":")[0];
As a bonus -- the base URL can then be redefined globally.
document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";
document.baseURI
returns base URL also respecting the value in <base/>
tag
https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
In case anyone would like to see this broken out into a very robust function
function getBaseURL() {
var loc = window.location;
var baseURL = loc.protocol + "//" + loc.hostname;
if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
// strip leading /
var pathname = loc.pathname;
if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
var pathParts = pathname.split("/");
if (pathParts.length > 0) {
for (var i = 0; i < pathParts.length; i++) {
if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
}
}
return baseURL;
}
The format is hostname/pathname/search
So the url is :
var url = window.location.hostname + window.location.pathname + window.location.hash
For your case
window.location.hostname = "stackoverflow.com"
window.location.pathname ="/questions/25203124/how-to-get-base-url-with-jquery-or-javascript"
window.location.hash = ""
So basically the baseurl = hostname = window.location.hostname
var getUrl = window.location;
var baseurl = getUrl.origin; //or
var baseurl = getUrl.origin + '/' +getUrl.pathname.split('/')[1];
But you can't say that the baseurl() of CodeIgniter(or php joomla) will return the same value, as it is possible to change the baseurl in the .htaccess file of these frameworks.
For example :
If you have an .htaccess file like this in your localhost :
RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
The $this->baseurl() will return http://localhost/CodeIgniter/