The location object in JavaScript helps in storing the information of current URL of the window object. It is a child object of the window object. The location object has two features called properties and methods. This blog covers all properties and methods which location object has with an example.
So let's get started,
🔷 HASH
The hash property sets or returns the anchor part of a URL, including the hash sign(#).
// Return the anchor part of a URL. Assume that the current URL is
// http://www.example.com/test.htm#part2:
var x = location.hash;
console.log(x);
// output
// #part2
🔷 HOSTNAME
The hostname property sets or returns the hostname of a URL.
var x = location.hostname;
console.log(x);
// output
// www.geeksforgeeks.com
🔷 ORIGIN
The origin property returns the protocol, hostname and port number of a URL.
// Return the protocol, hostname and port number of a URL.
// Assume that the current URL is
// https://www.w3schools.com:4097/test.htm#part2:
var x = location.origin;
console.log(x);
// output
// https://www.w3schools.com:4097
🔷 HOST
The host property sets or returns the hostname and port of a URL.
var x = location.host;
console.log(x);
// output
// www.geeksforgeeks.com
🔷 HREF
The href property sets or returns the entire URL of the current page.
var x = location.href;
console.log(x);
// output
// https://www.geeksforgeeks.com/
🔷 PATHNAME
The pathname property sets or returns the pathname of a URL.
// assuming url is
// https://www.w3schools.com/jsref/tryit.asp
var x = location.pathname;
console.log(x);
// output
// /jsref/tryit.asp
🔷 PORT
The port property sets or returns the port number the server uses for a URL.
var x = "Port: " + location.port;
console.log(x);
// output
// Port: 443
🔷 ASSIGN()
The assign method loads a new document.
location.assign("https://www.w3schools.com");
// output
// opens https://www.w3schools.com
🔷 REPLACE()
The replace() method replaces the current document with a new one. The difference between this method and assign(), is that replace() moves the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.
location.replace("https://www.w3schools.com");
// the replace() method replaces the current document with a new one
🔷 SEARCH()
The search property sets or returns the querystring part of a URL, including the question mark(?)
// returns the querystring part of a URL
// assume that the current URL is
// https://www.w3schools.com/submit.htm?email=someone@example.com:
var x = location.search;
// output
// ?email=someone@example.com
🔷 RELOAD()
The reload() method is used to reload the current document.
location.reload();
// the reload() method is used to reload the current document.
Hope you liked this!
Let's Get Connected 🤝:)