Cover Image for Window Location in JavaScript
109 views

Window Location in JavaScript

The window.location object provides information about the current URL and allows you to manipulate the browser’s location.

Here are some commonly used properties and methods of the window.location object:

  1. window.location.href: This property returns the entire URL of the current page, including the protocol, domain, path, and query parameters.
JavaScript
console.log(window.location.href);
// Example output: "https://www.example.com/index.html?id=123"
  1. window.location.protocol: This property returns the protocol (e.g., “http:”, “https:”, “file:”) of the current URL.
JavaScript
console.log(window.location.protocol);
// Example output: "https:"
  1. window.location.hostname: This property returns the hostname of the current URL.
JavaScript
console.log(window.location.hostname);
// Example output: "www.example.com"
  1. window.location.pathname: This property returns the path of the current URL.
JavaScript
console.log(window.location.pathname);
// Example output: "/index.html"
  1. window.location.search: This property returns the query string of the current URL, including the “?” character.
JavaScript
console.log(window.location.search);
// Example output: "?id=123"
  1. window.location.assign(url): This method loads a new URL by navigating to the specified url.
JavaScript
window.location.assign("https://www.example.com/page2.html");
  1. window.location.reload(): This method reloads the current page.
JavaScript
window.location.reload();
  1. window.location.replace(url): This method replaces the current URL with the specified url without adding a new entry to the browser’s history.
JavaScript
window.location.replace("https://www.example.com/page2.html");

These are just a few examples of how you can use the window.location object in JavaScript to access and manipulate the URL of the current page. You can explore more properties and methods available on the window.location object in the JavaScript documentation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS