URL.prototype.hash
Returns or sets the fragment identifier of the URL including the leading hash character
Syntax
url.hashReturn Value
A string containing the fragment (hash), or empty string
Examples
const url = new URL('https://example.com/page#section-2')
console.log(url.hash) // '#section-2'const url = new URL('https://example.com/docs')
url.hash = '#getting-started'
console.log(url.href)function getAnchor(urlStr: string): string {
const hash = new URL(urlStr).hash
return hash ? hash.slice(1) : ''
}Understanding URL.prototype.hash
The URL.prototype.hash method in JavaScript returns or sets the fragment identifier of the URL including the leading hash character. 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.hash. When called, it returns a string containing the fragment (hash), or empty string. Understanding when and how to use hash() helps you write more expressive, readable code.
Common use cases for URL.prototype.hash include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like url-search, url-pathname, url-href, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for URL.prototype.hash 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.searchReturns or sets the query string of the URL including the leading question mark
URL.prototype.pathnameReturns or sets the path section of the URL, which comes after the host and before the query string
URL.prototype.hrefReturns a string containing the whole URL, acting as a stringifier for the URL object
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.