When working with web applications, it is often necessary to manipulate URLs to perform various operations. In JavaScript, the location
object provides access to the current URL of the page and allows you to manipulate it using various properties and methods. In this article, we will explore the various URL properties of the location
object and how they can be used in JavaScript.
Understanding the Location Object
The location
object is a built-in object in JavaScript which represents the current URL of the page. It has several properties and methods that allow you to manipulate the URL, navigate to a new page, reload the current page, etc.
The location
object can be accessed using the window.location
property in JavaScript. It contains information about the URL of the current page, including the protocol, domain, port, pathname, search parameters, and hash.
URL Properties of Location Object
The following are the various URL properties of the location
object:
href
The href
property returns the entire URL of the current page, including the protocol, domain, port, pathname, search parameters, and hash. This property can also be used to navigate to a new page by assigning a new URL value to it.
// Get the current URL of the page
console.log(location.href);
// Navigate to a new page
location.href = "https://www.example.com/newpage";
protocol
The protocol
property returns the protocol of the current URL, such as http:
or https:
.
// Get the protocol of the current URL
console.log(location.protocol);
host
The host
property returns the domain name and port number of the current URL.
// Get the domain name and port number of the current URL
console.log(location.host);
hostname
The hostname
property returns the domain name of the current URL.
// Get the domain name of the current URL
console.log(location.hostname);
port
The port
property returns the port number of the current URL.
// Get the port number of the current URL
console.log(location.port);
pathname
The pathname
property returns the path and file name of the current URL.
// Get the path and file name of the current URL
console.log(location.pathname);
search
The search
property returns the query string of the current URL, including the ?
character.
// Get the query string of the current URL
console.log(location.search);
hash
The hash
property returns the fragment identifier of the current URL, including the #
character.
// Get the fragment identifier of the current URL
console.log(location.hash);
Conclusion
The location
object provides easy access to the current URL of the page and allows you to manipulate it using various properties and methods. In this article, we have explored the various URL properties of the location
object and provided code examples to illustrate their usage in JavaScript. Understanding these properties can help you to build more robust web applications that can navigate and manipulate URLs with ease.