← Back to all snippets
JAVASCRIPT

Validate URLs with a Comprehensive Regex

Implement a JavaScript regex pattern to validate various URL formats, including HTTP/HTTPS protocols, domains, ports, paths, and query parameters.

function isValidURL(url) {
  const urlRegex = /^(https?:\/\/)?([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(\/[^\s]*)?$/i;
  return urlRegex.test(url);
}

// Usage:
console.log(isValidURL("https://www.example.com/path?query=1")); // true
console.log(isValidURL("http://localhost:3000"));                // true
console.log(isValidURL("invalid-url"));                          // false
How it works: The `isValidURL` function uses a regular expression to validate if a string conforms to common URL patterns. It broadly covers optional `http(s)://` protocols, various domain formats (including subdomains and top-level domains of at least two characters), and optional paths with query parameters. The `i` flag makes the match case-insensitive.

Need help integrating this into your project?

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

Hire DigitalCodeLabs