Global / Window

URL

Creates and returns a URL object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string

Syntax

JavaScript
new URL(url, base?)

Parameters

ParameterTypeDescription
urlstringAn absolute or relative URL string
basestring | URLThe base URL to use when url is a relative URL

Return Value

A URL object with properties like hostname, pathname, searchParams, etc.

Examples

Basic Usage
const url = new URL('https://example.com/path?q=hello#section');
console.log(url.hostname); // 'example.com'
console.log(url.pathname); // '/path'
console.log(url.searchParams.get('q')); // 'hello'
Practical Example
const base = 'https://api.example.com';
const url = new URL('/users/123', base);
url.searchParams.set('fields', 'name,email');
console.log(url.toString());
// 'https://api.example.com/users/123?fields=name%2Cemail'
Advanced Usage
function isValidUrl(str: string): boolean {
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
}
console.log(isValidUrl('https://example.com')); // true
console.log(isValidUrl('not a url')); // false

Understanding URL

The URL method in JavaScript creates and returns a URL object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string. It belongs to the window object and is one of the most widely used methods for working with window values in modern JavaScript and TypeScript applications.

The method signature is new URL(url, base?). It accepts 2 parameters: url, base. When called, it returns a url object with properties like hostname, pathname, searchparams, etc.. Understanding when and how to use URL() helps you write more expressive, readable code.

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

Browser support for URL 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 Global / Window Methods

Other methods in the Global / Window object

Related Tools

More Global / Window Methods

Explore JavaScript Methods

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