Check if URL is Valid with canParse()
Here's an interesting method I just discovered.
On the URL object, we can access a method called canParse() (URL.canParse()) that lets us check that a given URL is valid.
How to
To use it, simply pass a URL to the URL.canParse() method and it will return true if valid, otherwise it will return false.
The syntax is pretty simple:
URL.canParse(url, optionalBaseValue)
The url, parameter being the URL and optionalBaseValue is an optional value that defaults to undefined.
I think some examples will help it make sense:
// Test valid URL
URL.canParse("https://codu.co/"): true
// Test relative URL (no base)
URL.canParse("/articles"): false
// Test relative URL with valid base URL
URL.canParse("/articles","https://codu.co/"): true
// Not a URL
URL.canParse("penis"): false
This can be handy in certain use cases such as constructing a URL with new URL("https://www.codu.co/"). Because if you pass new URL a invalid value it will throw a TypeError meaning usually I would wrap it in a try/catch block.
Here's a little example:
function createURLSafely(urlString) {
// Use URL.canParse() to check if the urlString is a valid URL
if (URL.canParse(urlString)) {
// If the URL is valid, construct the URL object
return new URL(urlString);
} else {
// If the URL is not valid, handle the case accordingly (e.g., return null or log an error)
console.error("Invalid URL:", urlString);
return null;
}
}
// Example usage:
const safeURL = createURLSafely("https://www.codu.co/");
if (safeURL) {
console.log("URL created successfully:", safeURL);
} else {
console.log("Failed to create URL.");
}
You can find the latest browser support information here.
