Click the button to display the hostname of the current URL.
``` ### Example 2: Redirecting by Modifying the Hostname You can redirect the user to a different domain on the same port and protocol by assigning a new value to `location.hostname`. ```javascript // Redirect the current page to a new domain function redirectToNewDomain() { window.location.hostname = "www.new-destination.com"; } ``` --- ## Technical Considerations ### `location.hostname` vs `location.host` It is easy to confuse `location.hostname` with `location.host`. Here is the key difference: * **`location.hostname`**: Returns only the domain name (e.g., `example.com`). It does **not** include the port number. * **`location.host`**: Returns the domain name *and* the port number if a non-default port is specified (e.g., `example.com:8080`). #### Comparison Table: For the URL: `https://example.com:8080/index.html` | Property | Returned Value | Description | | :--- | :--- | :--- | | `location.hostname` | `example.com` | Domain name only | | `location.host` | `example.com:8080` | Domain name + Port |Prop Loc Hostname
## JavaScript Location hostname Property
The `hostname` property of the `Location` object is a readable and writable string that sets or returns the domain name (host name) of the current URL.
---
## Syntax
```javascript
// Get the hostname
let domain = window.location.hostname;
// Set the hostname
window.location.hostname = "www.example.com";
```
### Return Value
A string representing the domain name of the current URL (for example, `www.wikipedia.org` or `localhost`). If the URL does not contain a domain name, an empty string is returned.
---
## Browser Support
| Property | Chrome | Edge/IE | Firefox | Safari | Opera |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `location.hostname` | Yes (All versions) | Yes (All versions) | Yes (All versions) | Yes (All versions) | Yes (All versions) |
The `hostname` property is fully supported by all major web browsers.
---
## Code Examples
### Example 1: Getting the Hostname of the Current Page
The following example retrieves the domain name of the current page and writes it to the document.
```html
Location hostname Example
YouTip