python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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  http://embed.plnkr.co/GTwlRC/preview

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>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <script>
        function getBaseURL() {
            var currentBaseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
            return currentBaseURL;
        };

        window.onload = function (e) {
            var baseURL = getBaseURL();
            alert(baseURL);
        };
    </script>
</head>
<body>
    <div>
        <h1>how to get base url in JavaScript?</h1>
        <h2><a href="http://www.code-sample.com/">http://www.code-sample.com/</a></h2>
    </div>
</body>
</html>

The live output , go to link  http://embed.plnkr.co/GTwlRC/preview




ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions