initialsFor static method

String initialsFor(
  1. String name, {
  2. int max = 2,
})

Derives up to two uppercase initials from name.

Handles single names and names with punctuation or extra whitespace.

Implementation

static String initialsFor(String name, {int max = 2}) {
  final parts = name
      .trim()
      .split(RegExp(r'[\s._-]+'))
      .where((p) => p.isNotEmpty)
      .toList();
  if (parts.isEmpty) return '?';
  if (parts.length == 1) {
    final single = parts.first;
    return single.characters.take(max).toString().toUpperCase();
  }
  return parts.take(max).map((p) => p.characters.first).join().toUpperCase();
}