location object refers to the current location or URL of the webpage. The
location object contains information about the navigation functionality of the document.
location object is accessible with both window and document, also it can be used without any reference because it is part of glocal object. Therefore
To get the current URL of the webpage use
href property of
Use this property with a
document object. Look at the following example.
Get Hostname From URL
There are 2 properties that return the hostname of URL one is
host property and another is
Both return the name of the host but the
host property also returns port number with hostname.
protocol property on
location to get protocol of the URL.
Look at the following example.
pathname property of the
location object returns the pathname of the URL.
We can get a query string from the
search property of the location object. It will return everything after ? including question marks.
URL assign and replace Method
replace() method of
location object to load another document by passing address of new document.
To load new documents, pass the URL as a parameter. Example:
There is another method
replace() which does the same task of loading new documents in the window but it does not create any entry of browser history, hence can't go to the previous page after using this but can go in forward direction.