A string or any other object with a stringifier — including, for example, an <a> or <area> element — that represents an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base will be ignored.
A string representing the base URL to use in cases where url is a relative URL. If not specified, it defaults to undefined.
Note: The url and base arguments will each be stringified from whatever value you pass, just like with other Web APIs that accept a string. In particular, you can use an existing URL object for either argument, and it will stringify to the object's href property.
url (in the case of absolute URLs) or base + url (in the case of relative URLs) is not a valid URL.
Examples
js
// Base URLs:let baseUrl ="https://developer.mozilla.org";letA=newURL("/", baseUrl);// => 'https://developer.mozilla.org/'letB=newURL(baseUrl);// => 'https://developer.mozilla.org/'newURL("en-US/docs",B);// => 'https://developer.mozilla.org/en-US/docs'letD=newURL("/en-US/docs",B);// => 'https://developer.mozilla.org/en-US/docs'newURL("/en-US/docs",D);// => 'https://developer.mozilla.org/en-US/docs'newURL("/en-US/docs",A);// => 'https://developer.mozilla.org/en-US/docs'newURL("/en-US/docs","https://developer.mozilla.org/fr-FR/toto");// => 'https://developer.mozilla.org/en-US/docs'// Invalid URLs:newURL("/en-US/docs","");// Raises a TypeError exception as '' is not a valid URLnewURL("/en-US/docs");// Raises a TypeError exception as '/en-US/docs' is not a valid URL// Other cases:newURL("http://www.example.com");// => 'http://www.example.com/'newURL("http://www.example.com",B);// => 'http://www.example.com/'newURL("","https://example.com/?query=1");// => 'https://example.com/?query=1' (Edge before 79 removes query arguments)newURL("/a","https://example.com/?query=1");// => 'https://example.com/a' (see relative URLs)newURL("//foo.com","https://example.com");// => 'https://foo.com/' (see relative URLs)
12Before Edge 79, query arguments in the base URL argument are removed when calling the URL constructor.
26
No
15
14.1
6In Safari 14 and earlier, calling the URL constructor with a base URL whose value is undefined causes Safari to throw a TypeError; see WebKit bug 216841.
4.4
25
26
14
14.5
6In Safari 14 and earlier, calling the URL constructor with a base URL whose value is undefined causes Safari to throw a TypeError; see WebKit bug 216841.