A Platform To Learn To Code

WINDOW LOCATION JAVASCRIPT



The location object refers to the current location or URL of the webpage. The location object contains information about the navigation functionality of the document.

The 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

  • window.location
  • document.location
  • location
are all valid way to use the location object.


Get URL Path Using Javascript

To get the current URL of the webpage use href property of location object.

Use this property with a document object. Look at the following example.

Example

Run the code

Output:


Get Hostname From URL

There are 2 properties that return the hostname of URL one is host property and another is hostname property.

Both return the name of the host but the host property also returns port number with hostname.

Example

Run the code

Output:


Get Protocol From URL Javascript

Use protocol property on location to get protocol of the URL.

Look at the following example.

Example

Run the code

Output:


Get Pathname From URL Javascript

The pathname property of the location object returns the pathname of the URL.

Example

Run the code

Output:


Get Query String Using Javascript

We can get a query string from the search property of the location object. It will return everything after ? including question marks.

Example

Run the code

URL assign and replace Method

Using assign() and 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: location.assign("https://www.tutorialstonight.com").

Example

Run the code

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.

Example

Run the code
Javascript History