Regular expressions (regex) can be used for URL validation, though they can be more complex and error-prone. Here's a simple regex pattern for validating URLs.
function validateURL(url) {
const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,}))|' + // domain name
'localhost|' + // localhost
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-zA-Z0-9%_@.&+=~]*)*$', 'i'); // port and path
return pattern.test(url);
}
console.log(validateURL('https://developerbreeze.com')); // true
console.log(validateURL('ftp://developerbreeze.com')); // false
console.log(validateURL('http://localhost:8080')); // true
console.log(validateURL('invalid-url')); // false