JAVASCRIPT

Validate and Extract URLs with Regex

Efficiently validate URLs and extract them from text using a JavaScript regular expression, useful for link parsing, input validation, and content analysis.

function isValidUrl(url) {
  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;
  return urlRegex.test(url);
}

function extractUrls(text) {
  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,})/gi;
  return text.match(urlRegex) || [];
}

// Usage:
console.log(isValidUrl("https://www.example.com")); // true
console.log(extractUrls("Check out example.com and https://test.org for details."));
// Expected: ["example.com", "https://test.org"]
How it works: This snippet provides two JavaScript functions for handling URLs. `isValidUrl` uses a comprehensive regular expression to check if a given string adheres to a common URL format. `extractUrls` uses a similar regex with the global flag to find and return all valid URLs present within a larger text string, which is highly useful for parsing user-generated content or articles.

Need help integrating this into your project?

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

Hire DigitalCodeLabs