JAVASCRIPT
Validate URLs Including Protocols and Domains
Efficiently validate full URL strings, including HTTP(S) protocols, domain names, and optional paths/query parameters, using a JavaScript regex pattern.
const isValidURL = (url) => {
// Regex for URL validation (supports http/https, optional www, domain, path, query, fragment)
const urlRegex = /^(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+\-~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+\-.~#?&//=]*)$/;
return urlRegex.test(url);
};
console.log(isValidURL("https://www.example.com/path?key=value#hash")); // true
console.log(isValidURL("http://example.org")); // true
console.log(isValidURL("www.sub.domain.net")); // true (without protocol)
console.log(isValidURL("invalid-url")); // false
How it works: This JavaScript function uses a regular expression to validate if a given string is a well-formed URL. It accounts for optional `http://` or `https://` protocols, optional `www.` subdomain, a valid domain name, and allows for paths, query parameters, and fragments. The `test()` method provides a quick check for structural validity.