JAVASCRIPT

Validate URLs Using a Regular Expression

Implement a JavaScript regex pattern to validate URLs, ensuring they follow a standard format including scheme, domain, and optional path for web links.

const urlRegex = /^(https?:\/\/)?([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}(\/?[-a-zA-Z0-9@:%._\+~#?&//=]*)?$/;

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

console.log(isValidURL("https://www.google.com"));   // true
console.log(isValidURL("http://example.org/path/file.html?id=1")); // true
console.log(isValidURL("invalid-url"));              // false
console.log(isValidURL("ftp://bad-protocol.com"));   // false
How it works: This regular expression pattern checks if a string is a valid URL. It supports optional 'http://' or 'https://' protocols, validates the domain structure (including subdomains and TLDs), and allows for optional paths, query parameters, and fragments. It helps ensure that user-provided links are well-formed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs