JAVASCRIPT

URL Validation and Protocol Extraction

Validate full URLs, including protocol and optional path, and extract the protocol using JavaScript regex for link verification and parsing.

function parseURL(url) {
  const urlRegex = /^(?<protocol>https?:\/\/)(?<domain>[^\/]+)(?<path>.*)?$/i;
  const match = url.match(urlRegex);

  if (match) {
    return {
      isValid: true,
      protocol: match.groups.protocol,
      domain: match.groups.domain,
      path: match.groups.path || ''
    };
  } else {
    return { isValid: false };
  }
}

// Examples:
console.log(parseURL('https://www.example.com/path/to/page?id=123'));
// { isValid: true, protocol: 'https://', domain: 'www.example.com', path: '/path/to/page?id=123' }
console.log(parseURL('http://localhost:3000'));
// { isValid: true, protocol: 'http://', domain: 'localhost:3000', path: '' }
console.log(parseURL('ftp://invalid.com')); // { isValid: false }
How it works: The `parseURL` function uses a regular expression with named capturing groups (`protocol`, `domain`, `path`) to validate and break down a URL. It specifically looks for URLs starting with `http://` or `https://`. If a match is found, it returns an object containing the validation status and extracted components; otherwise, it indicates an invalid URL. This is useful for robust link handling and data extraction.

Need help integrating this into your project?

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

Hire DigitalCodeLabs