To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.
The <base> tag specifies the base URL and/or target for all relative URLs in a document. The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.
You can simply call the window. location. href property which will return you the complete URL of the webpage including hostname, pathname, and query string. Let's test the JavaScript property practically.
Returns the base URL for the object.
This one will help you...
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
I think this will work well for you:
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );
This will get base url
var baseurl = window.location.origin+window.location.pathname;
This is an extremely old question, but here are the approaches I personally use ...
As many have already stated, this works for most situations.
var url = window.location.origin;
However, this simple approach can be used to strip off any port numbers.
var url = "http://" + location.host.split(":")[0];
Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...
var url = window.location.protocol + "//" + location.host.split(":")[0];
As a bonus -- the base URL can then be redefined globally.
document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With