JAVASCRIPT
Validate URL Format with Regular Expression
Use a JavaScript regular expression to accurately validate URLs, checking for common protocols and domain structures in web applications.
const isValidUrl = (url) => {
const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
return urlRegex.test(url);
};
console.log(isValidUrl("https://www.google.com")); // true
console.log(isValidUrl("ftp://ftp.example.org/dir")); // true
console.log(isValidUrl("invalid-url")); // false
How it works: This function employs a regular expression to validate if a string conforms to a common URL format. It checks for a protocol (http, https, ftp), followed by '://', and then a non-whitespace string representing the domain and path, with the 'i' flag for case-insensitive protocol matching.