toWordsFirstCharacters method
Returns the first numberOfCharacters
from the first letter of each word in the string.
The string is split into words based on the provided splitBy
pattern (default is whitespace).
The result contains the first letter of each word, up to the specified numberOfCharacters
.
If numberOfCharacters
is not provided, it includes the first letter of each word in the string.
Example:
String? text = "Hello Flutter Developer";
print(text.toWordsFirstCharacters(numberOfCharacters: 2)); // "HF"
print(text.toWordsFirstCharacters()); // "HFD"
String? emptyText = "";
print(emptyText.toWordsFirstCharacters()); // ""
Implementation
String toWordsFirstCharacters(
{int? numberOfCharacters, String splitBy = '\\s+'}) {
var initials = '';
if (validate().isEmptyOrNull) {
return '';
}
final nameParts = this!.trim().toUpperCase().split(RegExp(splitBy));
var num =
math.min(nameParts.length, numberOfCharacters ?? nameParts.length);
for (var i = 0; i < num; i++) {
initials += nameParts[i][0];
}
return initials;
}