URL.parse() and URL.canParse() replace custom try/catch URL wrappers in modern browsers
Web developers have long relied on hand-written try/catch wrappers around the new URL() constructor to safely handle invalid URLs from user input or third-party APIs. The native URL.parse() method now offers the same functionality, returning null instead of throwing a TypeError when given an invalid URL. A companion method, URL.canParse(), provides a simple boolean check for URL validity without constructing a URL object, making it suitable for form validation and redirect safety checks. Both methods accept an optional base URL argument, allowing relative paths to be resolved just as new URL() handles them. These two additions are available in all modern browsers and eliminate the need for teams to maintain their own divergent URL validation utilities.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in