camelCaseToWords function

String camelCaseToWords(
  1. String subject, [
  2. Pattern customPattern = defaultPattern,
  3. bool capitalizeWords = false
])

Implementation

String camelCaseToWords(String subject,
    [Pattern customPattern = defaultPattern, bool capitalizeWords = false]) {
  if (subject.isEmpty) {
    return '';
  }

  late RegExp pattern;

  if (customPattern is String) {
    pattern = RegExp(customPattern);
  } else if (customPattern is RegExp) {
    pattern = customPattern;
  }

  final matches = pattern.allMatches(subject);
  final words = <String>[];

  for (final match in matches) {
    final word = match.group(0);
    if (word != null) {
      words.add(word);
    }
  }

  if (words.isEmpty) {
    return '';
  }

  if (capitalizeWords) {
    // Capitalize each word
    for (var i = 0; i < words.length; i++) {
      final word = words[i];
      if (word.isNotEmpty) {
        words[i] = word[0].toUpperCase() + word.substring(1).toLowerCase();
      }
    }
  } else {
    // Original behavior
    final firstWord = words[0];
    if (firstWord.isNotEmpty) {
      words[0] = firstWord[0].toUpperCase() + firstWord.substring(1);
    }

    for (var i = 1; i < words.length; i++) {
      words[i] = words[i].toLowerCase();
    }
  }

  return words.join(' ');
}