
165 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:
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"
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:"
window.location.hostname
: This property returns the hostname of the current URL.
JavaScript
console.log(window.location.hostname);
// Example output: "www.example.com"
window.location.pathname
: This property returns the path of the current URL.
JavaScript
console.log(window.location.pathname);
// Example output: "/index.html"
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"
window.location.assign(url)
: This method loads a new URL by navigating to the specifiedurl
.
JavaScript
window.location.assign("https://www.example.com/page2.html");
window.location.reload()
: This method reloads the current page.
JavaScript
window.location.reload();
window.location.replace(url)
: This method replaces the current URL with the specifiedurl
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.