Tutorials Tonight's Logo


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.

function getURL() {
  var url = location.href;
  document.getElementById("output").innerHTML = url;
▶ Run the code


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.

function getHost() {
  var host = location.host;
  var hostName = location.hostname;
  document.getElementById("output").innerHTML = "Host - " + host + "
HostName - " + hostName; }
▶ Run the code


Get Protocol From URL Javascript

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

Look at the following example.

function getProtocol() {
  var Protocol = location.protocol;
  document.getElementById("output").innerHTML = "Protocol - " + Protocol;
▶ Run the code


Get Pathname From URL Javascript

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

function getPathname() {
  var Pathname = location.pathname;
  document.getElementById("output").innerHTML = "Pathname - " + Pathname;
▶ Run the code


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.

function getQueryString() {
  var queryString = location.search;
  document.getElementById("output").innerHTML = "queryString - " + queryString;
▶ 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").

function loadNew() {
▶ 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.

function loadNew() {
▶ Run the code

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.