← Back to all snippets
JAVASCRIPT

Validate Basic URL Format

A concise JavaScript regex pattern to validate a string as a basic URL. Checks for `http(s)://` protocol, valid domain structure, and overall URL format.

const urlRegex = /^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/[a-zA-Z0-9]+\.[^\s]{2,}|[a-zA-Z0-9]+\.[^\s]{2,})$/i;

function isValidURL(url) {
  return urlRegex.test(url);
}

console.log(isValidURL("https://www.example.com/path?query=1#hash")); // true
console.log(isValidURL("http://example.org"));                         // true
console.log(isValidURL("www.another-site.net/page"));               // true
console.log(isValidURL("local-dev.com"));                             // true (if considered a domain)
console.log(isValidURL("ftp://bad.url"));                             // false
console.log(isValidURL("not-a-url"));                                 // false
console.log(isValidURL("https://example"));                           // false (missing top-level domain)
How it works: This JavaScript snippet offers a robust regular expression to validate if a given string adheres to a common URL format. The pattern checks for optional `http` or `https` protocols, various domain name structures (including those starting with `www.`), and ensures that there's a top-level domain of at least two characters. This helps in validating user-provided links or ensuring consistency of external resource paths.

Need help integrating this into your project?

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

Hire DigitalCodeLabs