JAVASCRIPT

Validate URLs with Regex for Web Links

Implement a JavaScript function using regex to accurately validate URLs, supporting various protocols and domain structures for web links.

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

// Usage examples:
// console.log(isValidURL("http://www.example.com")); // true
// console.log(isValidURL("https://example.com/path/to/page?id=123")); // true
// console.log(isValidURL("www.sub.domain.net")); // true
// console.log(isValidURL("ftp://invalid.url")); // false (only http/https)
// console.log(isValidURL("example.com")); // true (missing protocol is allowed by this regex)
How it works: This JavaScript function `isValidURL` uses a regular expression to validate if a given string is a valid URL. The pattern allows for optional `http://` or `https://` protocols, requires a domain with a top-level domain (TLD) of at least two characters, and supports paths, queries, and fragments. It's designed to catch common valid URL formats while rejecting malformed ones. Backslashes within the regex literal (e.g., `\/` for a literal slash, `\.` for a literal dot, `\d` for a digit) are properly escaped as `\\/`, `\\.`, and `\\d` for JSON string representation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs