takeInitials method

String takeInitials(
  1. int count, {
  2. bool fill = false,
  3. bool withoutGarbage = false,
  4. List<String> garbage = garbage,
})

Implementation

String takeInitials(
  int count, {
  bool fill = false,
  bool withoutGarbage = false,
  List<String> garbage = garbage,
}) {
  var source = replaceAll(RegExp(r"\s+"), " ").trim();
  if (source.isNotEmpty) {
    if (withoutGarbage) {
      source = source
          .applyForIndexed<String>(
              garbage.length,
              (s, i) => s.replaceAll(
                    RegExp(r"\s*\" + garbage[i] + r"\s*",
                        caseSensitive: false),
                    " ",
                  ))
          .trim();
    }
    if (!source.contains(" ")) {
      return source.take(fill ? count : 1).trim().uppercase;
    }
    final initials = StringBuffer("");
    final sourceParts = source.split(" ");
    for (int i = 0; i < sourceParts.length; i++) {
      if (i == count) break;
      try {
        initials.write(sourceParts[i].trim().take());
      } catch (e) {
        $debugPrint(e, source);
      }
    }
    final _initials = initials.toString();
    return (fill && _initials.length < count
            ? source.take(count).trim()
            : _initials)
        .uppercase;
  }
  return source;
}