URL.canParse(): A Game-Changer in Web Development
A Fresh Approach to Ensuring URL Correctness in JavaScript Applications
URLs are everywhere. We use them a lot. But even though they are used a lot, we don’t have a good way to check if a string is a valid URL or not.
This is generally how we construct a URL object:
const url = new URL('https://www.google.com');
Now if you wonder, why should I care about this, I will simply use the URL as a string.
So to answer this, if we use a URL object then we will get some inbuilt methods to extract out the hostname, query params, etc.
// Using a URL object
let myURL = new URL('https://example.com/path?param1=value1#fragment');
console.log(myURL.hostname); // Output: example.com
myURL.pathname = '/newpath';
myURL.searchParams.set('param2', 'value2');
console.log(myURL.toString()); // Output: https://example.com/newpath?param1=value1¶m2=value2#fragment
Otherwise, we have to use regex and third-party libraries to validate and parse URL strings.
Now If we pass some invalid string in the URL constructor, then the JS engine will throw an error like this:
Now to handle these, since 2 decades we have been doing this:
try {
const url = new URL('JS Is Love');
} catch (e) {
console.log("JS Is Love but sorry it's not a valid URL");
}
But now we have a new way to check if a given string can make a valid URL or not.
URL.canParse()
if (URL.canParse('https://www.youtube.com/@rahuulmiishra')) {
const parsed = new URL('https://www.youtube.com/@rahuulmiishra');
}
URL.canParse() is a static method, which takes two arguments:
- URL(required): A URL is either a string or any object capable of being converted into a string, such as an <a> or <area> HTML element. It denotes an absolute or relative URL. In cases where the provided URL is relative, a base URL must be supplied and will serve as the reference point. If the URL is absolute, any specified base will be disregarded.
2. Base (Optional): The base parameter is an optional string that signifies the base URL to be utilized when the given URL is relative. If not explicitly defined, it defaults to undefined.
Test valid absolute URL
URL.canParse("https://developer.mozilla.org/"): true
Test relative URL with no base URL
URL.canParse("/en-US/docs"): false
Test relative URL with valid base URL
URL.canParse("/en-US/docs","https://developer.mozilla.org/"): true
Test relative URL with base URL supplied as a URL object
const urlObj = new URL('https://developer.mozilla.org/');
URL.canParse("/en-US/docs",urlObj);true
Conclusion:
Besides sounding right when you write it, using the URL
object makes more sense logically. The try-catch method might look okay in code, but it's not as easy on the eyes and doesn't match the way we naturally think about things.