preserveOnlyChars method

String preserveOnlyChars(
  1. String validChars, {
  2. String? replacementChar,
})

Returns a String that is made of some required chars only. Optionally the removed characters can be substituted with a replacement char

Example: '5,3798.00'.preserveOnlyChars('0123456789') returns '5379800' '5,3798.00'.preserveOnlyChars('0123456789', replacementChar: ' ') returns '5 3798 00'

Implementation

String preserveOnlyChars(String validChars, {String? replacementChar}) {
  /*    if (validChars == null) {
    throw ArgumentError('The validChar parameter cannot be null');
  } */
  replacementChar ??= '';
  final buffer = StringBuffer();
  for (var idx = 0; idx < length; idx++) {
    if (validChars.contains(this[idx])) {
      buffer.write(this[idx]);
    } else {
      if (replacementChar.isNotEmpty) {
        buffer.write(replacementChar);
      }
    }
  }
  return buffer.toString();
}