Location Object in JavaScript
Key Concepts
The location
object in JavaScript provides information about the current URL and allows you to manipulate it. The key concepts include:
- Properties: href, protocol, host, hostname, port, pathname, search, hash
- Methods: assign(), replace(), reload()
Properties
The location
object has several properties that provide details about the current URL:
href
: The entire URL.protocol
: The protocol of the URL (e.g., http:, https:).host
: The hostname and port of the URL.hostname
: The hostname of the URL.port
: The port number of the URL.pathname
: The path of the URL.search
: The query string of the URL.hash
: The fragment identifier of the URL.
let currentURL = location.href; let protocol = location.protocol; let host = location.host; let hostname = location.hostname; let port = location.port; let pathname = location.pathname; let search = location.search; let hash = location.hash;
Methods
The location
object provides methods to navigate and reload the page:
assign()
: Loads a new document.replace()
: Replaces the current document with a new one.reload()
: Reloads the current document.
location.assign("https://www.example.com"); location.replace("https://www.example.com"); location.reload();
Examples and Analogies
Imagine the location
object as a GPS navigator for your web browser:
- Properties: Think of the properties as different pieces of information about your current location, such as the street name (pathname), city (hostname), and postal code (search).
- Methods: Think of the methods as actions you can perform with the GPS, like setting a new destination (assign), updating your current location (replace), or refreshing the map (reload).
Here is a comprehensive example that uses all the key concepts:
let currentURL = location.href; console.log("Current URL: " + currentURL); location.assign("https://www.example.com/new-page"); location.replace("https://www.example.com/replace-page"); location.reload();
© 2024 Ahmed Baheeg Khorshid. All rights reserved.