capitalizeAllWordsFirstLetter static method

String capitalizeAllWordsFirstLetter(
  1. String s
)

Capitalize only the first letter of each word in a string Example: getx will make it easy => Getx Will Make It Easy Example 2 : this is an example text => This Is An Example Text

Implementation

static String capitalizeAllWordsFirstLetter(String s) {
  String lowerCasedString = s.toLowerCase();
  String stringWithoutExtraSpaces = lowerCasedString.trim();

  if (stringWithoutExtraSpaces.isEmpty) {
    return "";
  }
  if (stringWithoutExtraSpaces.length == 1) {
    return stringWithoutExtraSpaces.toUpperCase();
  }

  List<String> stringWordsList = stringWithoutExtraSpaces.split(" ");
  List<String> capitalizedWordsFirstLetter = stringWordsList
      .map(
        (word) {
          if (word.trim().isEmpty) return "";
          return word.trim();
        },
      )
      .where(
        (word) => word != "",
      )
      .map(
        (word) {
          if (word.startsWith(RegExp(r'[\n\t\r]'))) {
            return word;
          }
          return word[0].toUpperCase() + word.substring(1).toLowerCase();
        },
      )
      .toList();
  String finalResult = capitalizedWordsFirstLetter.join(" ");
  return finalResult;
}