new URL(), URL.canParse()
new URL(url)
new URL(url, base)
URL.canParse(url)
URL.canParse(url, base)Parse an absolute or relative URL, read its components, or test whether it can be parsed without throwing.
| Parameter | Description |
|---|---|
url | An absolute URL string, or a relative URL when base is provided. |
base | An absolute URL used to resolve a relative url. Required when url is relative. |
Returns: A URL object, or a boolean from canParse. The example prints selected components and two TypeError names.
Throws
TypeError— Thrown by the constructor when url cannot be parsed, including a relative URL without a base. Measured in Node.js 22.23.3.
- URL.canParse was available in this Node.js 22.23.3 runtime. Check MDN if you need older browser support.
const absolute = new URL("https://User:[email protected]:8080/path/page?q=1#hash");
console.log(absolute.href);
console.log(absolute.origin);
console.log(absolute.protocol, absolute.username, absolute.password);
console.log(absolute.host, absolute.hostname, absolute.port);
console.log(absolute.pathname, absolute.search, absolute.hash);
const relative = new URL("/rel?x=1", "https://example.com/base/dir");
console.log(relative.href);
console.log(URL.canParse("https://example.com/"));
console.log(URL.canParse("/rel", "https://example.com/"));
console.log(URL.canParse("not a url"));
try {
new URL("not a url");
} catch (error) {
console.log(error.name);
}
try {
new URL("/rel");
} catch (error) {
console.log(error.name);
}
Expected output
https://User:[email protected]:8080/path/page?q=1#hash
https://example.com:8080
https: User Pass
example.com:8080 example.com 8080
/path/page ?q=1 #hash
https://example.com/rel?x=1
true
true
false
TypeError
TypeError
Related: URLSearchParams