URL API is the standard interface, available as the URL class in browsers and Node.js, that parses a web address into named parts and can rebuild it safely. It is defined by the WHATWG URL Standard, and the same parsing rules apply in every conforming runtime. The constructor throws a TypeError when the string is not a valid absolute URL.
Calling new URL(input, base) runs the standard's parsing algorithm. The result is an object with writable properties: protocol, username, password, host, hostname, port, pathname, search, hash and href, plus the read-only origin and searchParams. Setting any property re-serializes the whole address, so href always stays consistent.
The parser normalizes as it goes:
const u = new URL('https://user:pw@Example.COM:443/a/./b/../c d?q=1&q=2#frag');
console.log(u.href);
console.log(u.origin, '|', u.host, '|', u.pathname, '|', u.search, '|', u.hash);
console.log(new URL('../x?y=1', 'https://example.com/a/b/c').href);
console.log(URL.canParse('/path'), URL.canParse('/path', 'https://a.com'));
try { new URL('/path'); } catch (e) { console.log(e.name, '|', e.message); }
Output from Node.js 22.22.0:
https://user:pw@example.com/a/c%20d?q=1&q=2#frag
https://example.com | example.com | /a/c%20d | ?q=1&q=2 | #frag
https://example.com/a/x?y=1
false true
TypeError | Invalid URL
Call URL.canParse(string), which returns true when the constructor would succeed and false when it would throw. It replaces the older try and catch around new URL. For a relative string, pass a base as the second argument, with the base as a second string. URL.parse(string) is a related static method that returns null instead of throwing. Both are newer than the constructor, so check your minimum browser and Node.js versions before relying on them.
It throws because the input is relative and no base was supplied, or because the host or scheme is malformed. The string /path fails on its own and works with a base. A bare host like example.com also fails, because without a scheme it is read as a relative path. Add the scheme and two slashes in front.