I want to capitalize each first letter from a sentence for Flutter..??
This is a capitalized sentence I'm expecting from This Is A Capitalized Sentence
CodePudding user response:
extension StringExtension on String {
String capitalizeByWord() {
if (trim().isEmpty) {
return '';
}
return split(' ')
.map((element) =>
"${element[0].toUpperCase()}${element.substring(1).toLowerCase()}")
.join(" ");
}
}
Use extension like this. So that you can use capitalizeByWord
on any String to convert it.
void main() async {
var data = 'this is a capitalized sentence';
print(data.capitalizeByWord()); // This prints the result 'This Is A Capitalized Sentence'
}
CodePudding user response:
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
So you can just call your extension like this:
import "string_extension.dart";
var someCapitalizedString = "someString".capitalize();
CodePudding user response:
Here is a well tested method that I made:
extension StringExtension on String {
/// Capitalize the first letter of each word in a string
///
/// dart /// String example = "hello world".capitalizeAllWordsFirstLetter(); // Hello World ///
String capitalizeAllWordsFirstLetter() {
String lowerCasedString = 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;
}}
print("this is an example sentence"); // This Is An Example Sentence