toTitleCase method

String toTitleCase()

Formats text to title case.

Example:

final text = 'hello there';
final formatted = text.toTitleCase();
// returns: 'Hello There'

Implementation

String toTitleCase() {
  final value = trim()
      .split(' ')
      .map((s) {
        s = s.withoutSymbols;
        if (s.isEmpty) return '';

        if (s.length == 1) return s.toUpperCase();

        final first = s[0].toUpperCase();
        final rest = s.substring(1).toLowerCase();

        return '$first$rest';
      })
      .join(' ')
      .trim();

  return value.isEmpty ? this : value;
}