How to get base url with jquery or javascript?

How to get base url with jquery or javascript?

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 following example:

The example may also change.


Solution 1:

This one will help you…

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + + "/" + getUrl.pathname.split('/')[1];

Solution 2:

I think it will ok for you

var base_url = window.location.origin;

var host =;

var pathArray = window.location.pathname.split( '/' );

Solution 3:

This will get base url

var baseurl = window.location.origin+window.location.pathname;

Solution 4:

This is not possible from javascript, because this is a server-side property. Javascript on the client cannot know where joomla is installed. The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value (phpBaseUrl).

You can then build the url like this:

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;

Solution 5:

I’ve run into this need on several Joomla project. The simplest way I’ve found to address is to add a hidden input field to my template:

<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />

When I need the value in JavaScript:

var baseurl = document.getElementById('baseurl').value;

Not as fancy as using pure JavaScript but simple and gets the job done.

Solution 6:

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/