toTitleCase property
String
get
toTitleCase
Converts the string to title case.
- This method splits the string by spaces, hyphens, or underscores, and capitalizes each word while making other letters lowercase.
- Returns a new string with each word capitalized and separated by a space.
Example:
"hello_world".toTitleCase; // Returns "Hello World"
Returns: A String in title case.
Implementation
String get toTitleCase {
// Split the string by non-alphabetic characters (spaces, underscores, etc.)
List<String> words = replaceAll(
RegExp(r'[_-]'), ' ') // Replace underscores and hyphens with spaces
.split(' ') // Split by spaces
.map((word) => word.trim()) // Remove any leading or trailing spaces
.where((word) => word.isNotEmpty) // Remove empty words if any
.toList();
// Capitalize the first letter of each word and join them back together
return words
.map((word) => word.isNotEmpty
? word[0].toUpperCase() + word.substring(1).toLowerCase()
: '')
.join(' ');
}