toTitleCase method

String toTitleCase()

Converts string to proper title case handling articles, conjunctions, and prepositions

Example:

"the lord of the rings".toTitleCase(); // Returns "The Lord of the Rings"
"a tale of two cities".toTitleCase(); // Returns "A Tale of Two Cities"

Implementation

String toTitleCase() {
  if (isEmpty) return this;
  final smallWords = {
    'a',
    'an',
    'and',
    'as',
    'at',
    'but',
    'by',
    'for',
    'if',
    'in',
    'nor',
    'of',
    'on',
    'or',
    'the',
    'to',
    'up',
    'yet'
  };

  final words = split(' ');
  return words.asMap().entries.map((entry) {
    final index = entry.key;
    final word = entry.value;

    if (word.isEmpty) return word;
    // Always capitalize first and last word
    if (index == 0 || index == words.length - 1) {
      return word.capitalize();
    }
    // Use lowercase for small words
    if (smallWords.contains(word.toLowerCase())) {
      return word.toLowerCase();
    }
    return word.capitalize();
  }).join(' ');
}