JAVASCRIPT
Validate URL Structure with Regex
Use this JavaScript regular expression to validate URLs, checking for correct protocol (http/https), domain, optional port, path, and query parameters.
const isValidURL = (url) => {
// Regex for URL validation including http/https, domain, port, path, query, and fragment.
const urlRegex = new RegExp(
/^(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(isValidURL("https://www.example.com/path?query=1#hash")); // true
console.log(isValidURL("http://localhost:3000")); // true
console.log(isValidURL("ftp://bad.protocol")); // false
How it works: This snippet defines a regular expression to validate if a given string is a valid URL. It supports both `http` and `https` protocols, various domain formats, optional subdomains, paths, query strings, and fragments. The `test()` method is used to quickly check for a match, providing a simple way to confirm URL formatting.