JAVASCRIPT
Validate URLs for Correct Format and Protocol
Implement a JavaScript regex pattern to validate URLs, ensuring they conform to standard formats and include a protocol (http/https) for accurate link handling.
const urlRegex = new RegExp(
/^(https?):\\/\\/[^\\s/$.?#].[^\\s]*$/i
);
function isValidURL(url) {
return urlRegex.test(url);
}
// Example usage:
// console.log(isValidURL("https://www.example.com/path")); // true
// console.log(isValidURL("http://localhost:3000")); // true
// console.log(isValidURL("example.com")); // false (needs protocol)
How it works: This JavaScript regex pattern is designed to validate URLs by checking for the presence of a 'http' or 'https' protocol followed by a valid domain and optional path. The `i` flag makes the match case-insensitive for the protocol. This ensures that only well-formed URLs with a specified protocol are considered valid.