URL

URL.prototype.hostname

Returns or sets the domain name of the URL without the port number

Syntax

JavaScript
url.hostname

Return Value

A string containing the hostname

Examples

Basic Usage
const url = new URL('https://www.example.com:3000/path')
console.log(url.hostname) // 'www.example.com'
Practical Example
const url = new URL('https://api.example.com/v2')
url.hostname = 'staging-api.example.com'
console.log(url.href)
Advanced Usage
function extractDomain(urlStr: string): string {
  return new URL(urlStr).hostname
}

Understanding URL.prototype.hostname

The URL.prototype.hostname method in JavaScript returns or sets the domain name of the URL without the port number. It belongs to the URL object and is one of the most widely used methods for working with url values in modern JavaScript and TypeScript applications.

The method signature is url.hostname. When called, it returns a string containing the hostname. Understanding when and how to use hostname() helps you write more expressive, readable code.

Common use cases for URL.prototype.hostname include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like url-origin, url-host, url-port, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for URL.prototype.hostname is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More URL Methods

Other methods in the URL object

Related Tools

More URL Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.