The URL()
constructor returns a newly created URL
object representing the URL defined by the parameters.
If the given base URL or the resulting URL are not valid URLs, the JavaScript TypeError
exception is thrown.
Note: This feature is available in Web Workers.
Syntax
const url = new URL(url [, base])
Parameters
url
- A
USVString
representing an absolute or relative URL. Ifurl
is a relative URL,base
is required, and will be used as the base URL. Ifurl
is an absolute URL, a givenbase
will be ignored. base
Optional- A
USVString
representing the base URL to use in caseurl
is a relative URL. If not specified, it defaults to''
.
Note: You can still use an existing URL
object for the base
, which stringifies itself to the object's href
property.
Exceptions
Exception | Explanation |
---|---|
TypeError |
url (in the case of absolute URLs) or base + url (in the case of relative URLs) is not a valid URL. |
Examples
// Base urls let m = 'https://developer.mozilla.org'; let a = new URL("/", m); // => 'https://developer.mozilla.org/' let b = new URL(m); // => 'https://developer.mozilla.org/' new URL('docs', b); // => 'https://developer.mozilla.org/docs' let d = new URL('/docs', b); // => 'https://developer.mozilla.org/docs' new URL('/docs', d); // => 'https://developer.mozilla.org/docs' new URL('/docs', a); // => 'https://developer.mozilla.org/docs' new URL('/docs', "https://developer.mozilla.org/fr-FR/toto"); // => 'https://developer.mozilla.org/docs' new URL('/docs', ''); // Raises a TypeError exception as '' is not a valid URL new URL('/docs'); // Raises a TypeError exception as '/docs' is not a valid URL new URL('http://www.example.com', ); // => 'http://www.example.com/' new URL('http://www.example.com', b); // => 'http://www.example.com/' new URL("//foo.com", "https://example.com") // => 'https://foo.com' (see relative URLs)
Specification
Specification | Status | Comment |
---|---|---|
URL The definition of 'URL.URL()' in that specification. |
Living Standard | Initial definition. |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
URL() constructor | Chrome Full support 19 | Edge Full support 12 | Firefox Full support 26 | IE No support No | Opera Full support 15 | Safari Full support 6 | WebView Android Full support ≤37 | Chrome Android Full support 25 | Firefox Android Full support 26 | Opera Android Full support 14 | Safari iOS Full support 6 | Samsung Internet Android Full support 1.5 |
Legend
- Full support
- Full support
- No support
- No support
See also
- The interface it belongs to:
URL
.