JavaScript

Validate URL

by @admin
9h ago
Apr 28, 2026
Public
Validates whether a string is a well-formed URL using the native URL constructor, which matches browser parsing behaviour exactly. Optionally restricts to specific protocols (defaults to http and https). No regex maintenance required — if the browser can parse it as a URL, this returns true.
JavaScript
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
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.