JAVASCRIPT
Validate URL Format (HTTP/HTTPS)
Discover a robust JavaScript regex pattern to validate web URLs, ensuring they begin with http:// or https:// and follow standard domain and path structures.
function isValidUrl(url) {
const urlRegex = /^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/[a-zA-Z0-9]+\.[^\s]{2,}|[a-zA-Z0-9]+\.[^\s]{2,})$/i;
return urlRegex.test(url);
}
// Usage:
console.log(isValidUrl("https://www.example.com/path?query=1")); // true
console.log(isValidUrl("ftp://example.com")); // false
How it works: This JavaScript function `isValidUrl` uses a comprehensive regular expression to validate if a given string is a correctly formatted web URL. It specifically looks for URLs starting with `http://` or `https://`, including variations with and without "www", and ensures a valid domain structure. This helps in validating user-submitted links in forms or when parsing text content, preventing malformed links.