URL.prototype.port
Returns or sets the port number of the URL as a string
Syntax
url.portReturn Value
A string containing the port number, or empty string for default ports
Examples
const url = new URL('https://example.com:8080/path')
console.log(url.port) // '8080'const url = new URL('https://example.com/path')
console.log(url.port) // '' (default port 443)const url = new URL('http://localhost:3000')
url.port = '8080'
console.log(url.href) // 'http://localhost:8080/'Understanding URL.prototype.port
The URL.prototype.port method in JavaScript returns or sets the port number of the URL as a string. 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.port. When called, it returns a string containing the port number, or empty string for default ports. Understanding when and how to use port() helps you write more expressive, readable code.
Common use cases for URL.prototype.port include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like url-hostname, url-host, url-origin, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for URL.prototype.port 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
URL.prototype.hostnameReturns or sets the domain name of the URL without the port number
URL.prototype.hostReturns or sets the host portion of the URL including the port number if specified
URL.prototype.originReturns a string containing the origin of the URL, which includes the scheme, domain, and port
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.