Definition and application
Please note that the value of the property may be null , in the event that it is not possible to obtain an absolute URL , the value of the property may change over time.
The base URL is used to resolve relative URLs when the browser needs to obtain an absolute URL , such as when processing the src attribute of an HTML <img> , or the xlink:href attribute in XML . In general, the base URL is simply the location of the document, but many factors can influence it, including the <base> in HTML and the xml:base attribute in XML .
The base URL of the document
The document’s base URL is, by default, the document’s address (displayed by the browser and available in the location property of the Window object ). The base URL may change from the default value in the following cases:
- When an HTML <base> is encountered in a document.
- When it’s a new document created dynamically.
- See URLs in HTML Life for details.
You can use document .baseURI to get the base URL of the document. Note that getting a base URL for a document may return different URLs over time if the <base> tag changes, or if the location of the document changes.
The base URL of the element
The base URL of an element in an HTML document is usually equal to the base URL of the document in which the node resides. You can use element .baseURI to get the element’s base URL . If the document contains xml:base attributes (which should not be done in HTML documents ), then calling element .baseURI takes the xml:base attributes of the element’s parents into account when calculating the base URL .
const baseURI = node .baseURI; node --Node _
Document Object Model (DOM) Level 3
// get the base URL of the document document .baseURI // get the base URL of the element element .baseURI
For example, something like:
I would like to get:
Regular Expression Better? If so, what operator can I use to assign the base URL extracted from this string to a new variable?
Some people complain that it does not take the protocol into account. So I decided to update the code, since it is marked as an answer. For those who like one-line code… well sorry, why do we use code minimizers, the code should be human readable, and this way is better… in my opinion.
var pathArray = location.href.split( '/' );
var protocol = pathArray;
var host = pathArray;
var url = protocol + '//' + host;
Or use solution from below.
WebKit-based browsers, Firefox since version 21 and current versions of Internet Explorer (IE 10 and 11) implement
location.origin includes the protocol on the domain and additionally the port from the URL.
e.g., location.origin from
For target browsers without support for location.origin, use the following short polyfill:
if (typeof location.origin === 'undefined')
location.origin = location.protocol + '//' + location.host;