JAVASCRIPT
Regex for Validating URLs
Master URL validation in JavaScript with a comprehensive regular expression to check for correct web address formats, including protocols, domains, and paths.
function isValidURL(url) {
// Regex adapted from various sources, covers http(s), optional www, domain, TLD, and optional path/query/fragment.
const urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
return urlRegex.test(url);
}
console.log(isValidURL('https://www.example.com')); // true
console.log(isValidURL('http://example.org/path/file.html?q=test#hash')); // true
console.log(isValidURL('www.sub.domain.co')); // true (optional protocol)
console.log(isValidURL('just-a-string')); // false
console.log(isValidURL('ftp://invalid.com')); // false (only http/https)
How it works: The `isValidURL` function uses a regular expression to determine if a given string is a valid URL. This regex supports both 'http' and 'https' protocols (optional), common domain structures, top-level domains, and optional paths, queries, or fragments. It's a useful tool for validating links provided by users or parsed from external content, ensuring they conform to a web standard.