titleFromCamel method

String titleFromCamel()

Converts camelCase / PascalCase to Title Case Keeps abbreviations (3+ consecutive capitals) intact

Implementation

String titleFromCamel() {
  if (isEmpty) return this;

  final withSpaces = replaceAllMapped(
    RegExp(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])'),
    (_) => ' ',
  );

  return withSpaces
      .trim()
      .split(RegExp(r'\s+'))
      .map((w) {
        // Preserve acronyms (3+ uppercase letters)
        if (RegExp(r'^[A-Z]{3,}$').hasMatch(w)) {
          return w;
        }
        return w[0].toUpperCase() + w.substring(1).toLowerCase();
      })
      .join(' ')
      .replaceAll("_", " ");
}