JAVASCRIPT

Validate a Full URL Structure

Learn to validate a complete URL string, including protocol, domain, path, query, and hash, using a robust regular expression in JavaScript.

function isValidURL(url) {
  const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
  return urlRegex.test(url);
}

// Examples
console.log(isValidURL("https://www.example.com/path/to/page?query=test#hash")); // true
console.log(isValidURL("http://localhost:3000/api")); // true
console.log(isValidURL("ftp://ftp.example.org/file.txt")); // true
console.log(isValidURL("invalid-url")); // false
console.log(isValidURL("www.example.com")); // false (missing protocol)
How it works: This JavaScript function `isValidURL` uses a regular expression to check if a given string conforms to a general URL structure. It validates the presence of a protocol (http, https, or ftp), followed by `://`, a non-whitespace domain/host, and then any valid URL characters for path, query, and hash. The `i` flag makes the pattern 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