URL

URL.prototype.toString

Returns a string containing the whole URL, equivalent to URL.href

Syntax

JavaScript
url.toString()

Return Value

A string of the full URL

Examples

Basic Usage
const url = new URL('https://example.com/path')
console.log(url.toString())
Practical Example
const url = new URL('/api/v1', 'https://example.com')
url.searchParams.set('key', 'abc')
console.log(url.toString())
Advanced Usage
function buildUrl(base: string, path: string, params: Record<string, string>) {
  const url = new URL(path, base)
  Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v))
  return url.toString()
}

Understanding URL.prototype.toString

The URL.prototype.toString method in JavaScript returns a string containing the whole URL, equivalent to URL.href. 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.toString(). When called, it returns a string of the full url. Understanding when and how to use toString() helps you write more expressive, readable code.

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

Browser support for URL.prototype.toString 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.