function isValidUrl(str, protocols = ['http:', 'https:']) {
try {
const url = new URL(str);
return protocols.length === 0 || protocols.includes(url.protocol);
} catch {
return false;
}
}
// Usage
console.log(isValidUrl('https://example.com')); // true
console.log(isValidUrl('ftp://files.example.com')); // false (http/https only)
console.log(isValidUrl('ftp://files.example.com', [])); // true (any protocol)
console.log(isValidUrl('not a url')); // false
Create a free account and build your private vault. Share publicly whenever you want.