getInitials static method
Returns the initials of a given name.
name is the full name
maxLength is the maximum length of the initials. Defaults to 4.
The method will return the first letter of each word (ignoring non-alphabetic
words) up to a maximum of maxLength characters. If the initials length is
greater than maxLength, the method will return the first maxLength characters.
Implementation
static String getInitials(String name, {int maxLength = 4}) {
// Remove all non-alphanumeric characters and split the string into words
List<String> words =
name.replaceAll(RegExp(r'[^A-Za-z0-9\s]'), '').trim().split(' ');
// Initialize empty string for the initials
String initials = '';
// Loop through each word
for (var word in words) {
// Check if the word is not empty
if (word.isNotEmpty) {
// If the word contains numbers, add it to the initials
if (RegExp(r'\d').hasMatch(word)) {
initials += word;
} else {
// Otherwise add the first letter of the word to the initials
initials += word[0].toUpperCase();
}
}
// Break the loop if the initials length is greater than maxLength
if (initials.length >= maxLength) {
break;
}
}
// Return the initials. If the length is greater than maxLength, return a substring of maxLength length.
return initials.length > maxLength
? initials.substring(0, maxLength)
: initials;
}