get base url in JavaScript

How to get base URL in JavaScript?

Hello everyone, I am going to share the code sample to get base URL using the JavaScript. I think this one is very interesting stuff when you developing the web applications.

Using this no need to writing  on local base URL and server base URL again and again, The below code help me to prevent the re writing the base URL again and again actually.

The live output, go to link

The go detail as given below.

var  _baseURL;

//This method id used to get the base URL for global constant.
function getBaseURL() {   
   _baseURL= location.protocol + "//" + location.hostname +
       (location.port && ":" + location.port) + "/";
   return baseURL;

The live demo example code as given below

<!DOCTYPE html>
    <link rel="stylesheet" href="style.css">
        function getBaseURL() {
            var currentBaseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
            return currentBaseURL;

        window.onload = function (e) {
            var baseURL = getBaseURL();
        <h1>how to get base url in JavaScript?</h1>
        <h2><a href=""></a></h2>

The live output , go to link


Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog -
My Books - Book 1 and Book 2 Powered by Blogger.