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
new URL(url, base?)Parameters
| Parameter | Type | Description |
|---|---|---|
| url | string | An absolute or relative URL string |
| base | string | URL | The base URL to use when url is a relative URL |
Return Value
A URL object with properties like hostname, pathname, searchParams, etc.
Examples
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'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'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')); // falseUnderstanding 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
encodeURIComponentEncodes a URI component by replacing certain characters with UTF-8 escape sequences
encodeURIEncodes a URI by replacing certain characters with UTF-8 escape sequences, but preserves characters that are part of URI syntax
fetchStarts the process of fetching a resource from the network, returning a promise that resolves to a Response object
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.