JAVASCRIPT

Validate URLs with Regex in JavaScript

Discover how to validate URLs using a comprehensive regular expression in JavaScript, ensuring links are properly formatted for web content.

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

// Examples:
// console.log(isValidURL("http://www.example.com"));   // true
// console.log(isValidURL("https://example.com/path")); // true
// console.log(isValidURL("www.sub.domain.org"));       // true
// console.log(isValidURL("invalid-url"));             // false
How it works: This JavaScript function checks if a given string is a valid URL using a regular expression. The regex accounts for optional `http://` or `https://` protocols, a domain name with subdomains, a top-level domain, and optional paths or query parameters. It helps in ensuring that user-provided links adhere to common URL structures, making it useful for form validation and content parsing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs