JAVASCRIPT
Validate URL Format
Validate URLs including http/https protocols, optional www, domains, paths, queries, and fragments using a comprehensive JavaScript regex pattern for web applications.
const urlRegex = /^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/[a-zA-Z0-9]+\.[^\s]{2,}|[a-zA-Z0-9]+\.[^\s]{2,})$/i;
function isValidURL(url) {
return urlRegex.test(url);
}
// Examples:
console.log(isValidURL("https://www.example.com")); // true
console.log(isValidURL("http://example.org/path?query=1")); // true
console.log(isValidURL("www.sub.domain.co")); // true
console.log(isValidURL("just-a-string")); // false
console.log(isValidURL("ftp://ftp.server.com")); // false (only http/https)
How it works: This comprehensive regex pattern validates various forms of URLs, including those with 'http://', 'https://', or 'www.' prefixes, as well as domain-only inputs. It uses non-capturing groups `(?:...)` and negative lookahead `(?!www)` to handle different permutations. The `i` flag makes the matching case-insensitive. While robust, real-world URL validation can be extremely complex, but this covers most common web use cases.