mask method

String mask({
  1. int unmaskedStart = 0,
  2. int unmaskedEnd = 0,
  3. String maskChar = '*',
})

Masks characters with maskChar, preserving unmaskedStart characters at the beginning and unmaskedEnd characters at the end.

'1234567890'.mask(unmaskedStart: 2, unmaskedEnd: 2); // '12******90'

Implementation

String mask({
  int unmaskedStart = 0,
  int unmaskedEnd = 0,
  String maskChar = '*',
}) {
  if (unmaskedStart < 0) {
    throw ArgumentError.value(
      unmaskedStart,
      'unmaskedStart',
      'must not be negative',
    );
  }
  if (unmaskedEnd < 0) {
    throw ArgumentError.value(
      unmaskedEnd,
      'unmaskedEnd',
      'must not be negative',
    );
  }

  if (length <= unmaskedStart + unmaskedEnd) return this;

  final start = substring(0, unmaskedStart);
  final end = substring(length - unmaskedEnd);
  final maskedLength = length - unmaskedStart - unmaskedEnd;
  final masked = maskChar * maskedLength;

  return '$start$masked$end';
}