toTitleCase function
Converts a string input
to title case format.
If the input
is null or empty, an empty string is returned.
The function trims leading and trailing whitespace from the input
and splits it into an array of words using whitespace as the delimiter.
It then capitalizes the first letter of each word and converts the
remaining characters in each word to lowercase. Consecutive spaces
are skipped, preserving only non-empty words.
Example: toTitleCase('hello world') => 'Hello World' toTitleCase('the quick brown fox') => 'The Quick Brown Fox'
Returns the converted string in title case format.
Implementation
String toTitleCase(String? input) {
if (input == null || input.isEmpty) return '';
final words = input.trim().split(RegExp(r'\s+'));
final capitalizedWords = words.where((word) => word.isNotEmpty).map((word) {
final firstLetter = word[0].toUpperCase();
final restOfWord = word.substring(1).toLowerCase();
return firstLetter + restOfWord;
});
return capitalizedWords.join(' ');
}