initials method

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

Returns initials from a name string (up to max characters).

'John Doe'.initials()        // 'JD'
'Mary Jane Watson'.initials(max: 3) // 'MJW'

Implementation

String initials({int max = 2}) {
  if (isEmpty) return '';
  final words = trim().split(RegExp(r'\s+'));
  return words
      .take(max)
      .map((w) => w.isNotEmpty ? w[0].toUpperCase() : '')
      .join();
}