JAVASCRIPT
Validate URLs for Correct Formatting
Use a JavaScript regex pattern to validate URLs, ensuring they adhere to standard web address formats, including protocols and domain structures.
const validateUrl = (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);
};
console.log(validateUrl("https://www.example.com/path?query=1")); // true
console.log(validateUrl("http://example.org")); // true
console.log(validateUrl("invalid-url")); // false
How it works: This regular expression validates a string as a URL. It covers various formats including `http://`, `https://`, `www.`, and even bare domain names. The pattern ensures the presence of a domain name and a valid top-level domain, making it robust for typical web development needs. The `i` flag makes the regex case-insensitive.