extractDomainWithSuffix function

String extractDomainWithSuffix(
  1. String hostname,
  2. String publicSuffix
)

Given a hostname and its public suffix, extract the general domain.

Implementation

String extractDomainWithSuffix(String hostname, String publicSuffix) {
  // Locate the index of the last '.' in the part of the `hostname` preceding
  // the public suffix.
  //
  // examples:
  //   1. not.evil.co.uk  => evil.co.uk
  //         ^    ^
  //         |    | start of public suffix
  //         | index of the last dot
  //
  //   2. example.co.uk   => example.co.uk
  //     ^       ^
  //     |       | start of public suffix
  //     |
  //     | (-1) no dot found before the public suffix
  int publicSuffixIndex = hostname.length - publicSuffix.length - 2;
  int lastDotBeforeSuffixIndex = hostname.lastIndexOf('.', publicSuffixIndex);

  // No '.' found, then `hostname` is the general domain (no sub-domain)
  if (lastDotBeforeSuffixIndex == -1) {
    return hostname;
  }

  // Extract the part between the last '.'
  return hostname.substring(lastDotBeforeSuffixIndex + 1);
}