How to get Base URL or Root URL using Javascript

WebTechRiser.com > 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,

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 the deeper folder, like,

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

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

http://localhost/

and

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

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.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);
        }

Happy coding!

Also read:  React useCallback and useMemo Hook
Category Javascript

Leave Your Comment

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