brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: URL.parse() returns null for a bad URL, so you can drop the try/catch

Javascript
~/tips/tip-js-url-parse-no-try-catch

URL.parse("not a url"); // null

Validate and resolve URLs without exceptions in your normal code path.

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()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { shareButton.addEventListener("click", async () => { All Javascript tips (40) All topics

Link