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
- Pattern Breakdown:
^(https?:\\/\\/)?
: Matches the protocol (http://
or https://
).(([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,}))
: Matches domain names.localhost
: Matches localhost
.((\\d{1,3}\\.){3}\\d{1,3})
: Matches IPv4 addresses.(\\:\\d+)?
: Matches the port number.(\\/[-a-zA-Z0-9%_@.&+=~]<em>)</em>$
: Matches the path.