How to get Base URL or Root URL using Javascript > Javascript > How to get Base URL or Root URL using Javascript

I ran into a situation while developing a website where I needed to get a specific part of the URL. Think of a URL, http://localhost/testjs/index.html. I want to extract both the base URL and the root URL which are,




in my case.

If I relocate the website in the future, my script will continue to work. Suppose, if I move into the deeper folder, like,


My script will provide me with the correct folder names without any error, meaning that the script will dynamically calculate the depth of the folder structure and provide me with the correct URL. In this case, it will provide me




as root and base URL respectively.

After some Googling, I found a few solutions and come up with two functions which will provide the root URL and base URL. They are written below.

For Root URL:

function getRootUrl() {
            document.getElementById('rootresult').innerHTML += 
                ? window.location.origin + '/'
                : window.location.protocol + '/' + + '/';

For Base URL:

function getBaseUrl() {
            var re = new RegExp(/^.*\//);
            document.getElementById('baseresult').innerHTML += re.exec(window.location.href);

Happy coding!

Also read:  Creating a Hamburger Menu: Hands-on Tutorial and Examples
Category Javascript

Leave Your Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.