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 URL. Think of a URL, http://localhost/testjs/index.html. I want to extract both the base URL and the root URL which are,

    http://localhost/

and

    http://localhost/testjs/

in my case.

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

    http://localhost/testjs/deeperfolder/moredeeperfolder/index.html

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

    http://localhost/

and

    http://localhost/testjs/deeperfolder/moredeeperfolder/

as root and base URL respectively.

After some Googling, I found few solution and come up with two function which will provide root URL and base URL. They are written below.

 

For Root URL:

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

 

For Base URL:

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

 

Please feel free to download the attached file, move the file to a folder of your web root and run it. I hope you will find the pieces of codes useful.

Happy coding!

Other articles of this category:

There is no article found in this category.