JAVASCRIPT
Validate Full URL Structure with Regex
Learn to validate complete URL structures, including protocol, domain, path, and query parameters, using a powerful JavaScript regex for reliable input checks.
const urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
function isValidUrl(url) {
return urlRegex.test(url);
}
// Example usage:
// console.log(isValidUrl("https://www.example.com/path/to/page?id=123")); // true
// console.log(isValidUrl("http://localhost:3000")); // true
// console.log(isValidUrl("not-a-url")); // false
How it works: This regular expression is designed to validate common URL formats. It supports optional `http://` or `https://` protocols, captures the domain name and top-level domain, and allows for paths, filenames, and optional trailing slashes. It's a useful pattern for verifying user-provided URLs in web forms, ensuring they adhere to a standard structure.