new URL() throws a TypeError on anything it cannot parse, which means every bit of user input needs a try/catch around it. URL.parse() does the same parsing and returns null on failure.
URL.parse("not a url"); // null
URL.parse("/docs?page=2", "https://example.com/blog/").href;
// "https://example.com/docs?page=2"
const url = URL.parse(form.website.value);
if (!url || !["https:", "http:"].includes(url.protocol)) {
showError("Enter a full http or https address.");
}
URL.canParse("https://example.com"); // true
The second argument is a base URL for relative input, just like with the constructor. A relative path without a base fails, which is often what you want when people should type a full address.
I wouldn’t skip the protocol check in the example. javascript:alert(1) and data: URLs parse fine, so “it parses” never means “it is safe to put in a link”. For a plain yes or no without the object, URL.canParse() exists too.
Support for URL.parse(): Chrome 126, Firefox 126, Safari 18 and Node.js 22.1. canParse came a bit earlier (Chrome 120, Firefox 115, Safari 17). For older browsers, the try/catch around new URL() is the fallback.
Further reading: MDN: URL.parse(), MDN: URL.canParse()