JAVASCRIPT
Validate URLs with a Comprehensive Regex Pattern
Use this JavaScript regex to validate various URL formats, including protocols, domains, paths, queries, and fragments, crucial for input sanitization.
const urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
function validateURL(url) {
return urlRegex.test(url);
}
console.log(validateURL('http://www.example.com')); // true
console.log(validateURL('https://example.com/path/to/page?id=123')); // true
console.log(validateURL('www.sub.domain.net')); // true (optional protocol)
console.log(validateURL('ftp://invalid.protocol')); // false
console.log(validateURL('just-a-string')); // false
How it works: This regex is designed to validate common URL formats. It optionally matches `http://` or `https://` protocols, then captures the domain name, followed by the top-level domain. It also accounts for optional paths, query parameters, and fragments. The `?` makes the protocol optional, allowing `www.example.com` to pass. While comprehensive, extremely complex or highly specific URL schemes might require a more tailored pattern or URL parsing libraries.