mask method

String mask(
  1. int keepStart,
  2. int keepEnd, [
  3. String maskChar = '*'
])

Masks a portion of the string, useful for sensitive data

Example:

"1234567890".mask(4, 4, '*'); // Returns "1234******"
"johndoe@example.com".mask(3, 10, '*'); // Returns "joh**********@example.com"

Implementation

String mask(int keepStart, int keepEnd, [String maskChar = '*']) {
  if (isEmpty) return this;
  if (keepStart < 0) keepStart = 0;
  if (keepEnd < 0) keepEnd = 0;
  if (keepStart + keepEnd >= length) return this;

  final visibleStart = substring(0, keepStart);
  final visibleEnd = keepEnd > 0 ? substring(length - keepEnd) : '';
  final masked = maskChar * (length - keepStart - keepEnd);

  return '$visibleStart$masked$visibleEnd';
}