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.
new URL(url)
new URL(url, base)
url
-
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.
-
base
Optional
-
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.
let baseUrl = "https://developer.mozilla.org";
let A = new URL("/", baseUrl);
let B = new URL(baseUrl);
new URL("en-US/docs", B);
let D = new URL("/en-US/docs", B);
new URL("/en-US/docs", D);
new URL("/en-US/docs", A);
new URL("/en-US/docs", "https://developer.mozilla.org/fr-FR/toto");
new URL("/en-US/docs", "");
new URL("/en-US/docs");
new URL("http://www.example.com");
new URL("http://www.example.com", B);
new URL("", "https://example.com/?query=1");
new URL("/a", "https://example.com/?query=1");
new URL("//foo.com", "https://example.com");