capitalize method
Capitalizes the first letter of the string, leaving the rest of the string unchanged.
If lowerCaseRemaining
is set to true
, all characters after the first one are converted
to lowercase.
Parameters:
lowerCaseRemaining
: A boolean value. Iftrue
, converts the remaining characters to lowercase. Defaults tofalse
.
Returns: A new string with the first letter capitalized. Returns the original string if it is empty.
Example:
'lowercase'.capitalize(); // Returns 'Lowercase'
'mIxEd'.capitalize(lowerCaseRemaining: true); // Returns 'Mixed'
''.capitalize(); // Returns ''
Implementation
String capitalize({bool lowerCaseRemaining = false}) {
if (isEmpty) {
// failed null or empty check
return this;
}
// https://stackoverflow.com/questions/29628989/how-to-capitalize-the-first-letter-of-a-string-in-dart
if (lowerCaseRemaining) {
return '${this[0].toUpperCase()}${substring(1).toLowerCase()}';
}
return '${this[0].toUpperCase()}${substring(1)}';
}