JAVASCRIPT

Validate URLs

Implement a JavaScript function to validate URLs, checking for common protocols (http/https) and a valid domain structure.

function isValidURL(url) {
  const urlRegex = new RegExp(
    /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
  );
  return urlRegex.test(url);
}

// Usage:
// console.log(isValidURL("https://www.example.com")); // true
// console.log(isValidURL("http://sub.domain.net/path?query=1")); // true
// console.log(isValidURL("example.com")); // true (optional http/https)
// 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 optionally matches `http://` or `https://`, followed by a domain name and an optional path. This regex provides a common level of validation for web addresses, suitable for many form inputs or link checks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs