mreNormalizePhoneInput function

String mreNormalizePhoneInput(
  1. String input
)

Returns input reduced to what a phone number can hold: ASCII digits and a plus at the very start.

Arabic-Indic (٠١٢٣), Persian (۰۱۲۳) and full-width (0123) digits become ASCII digits. Spaces, dashes, brackets and dots are dropped, so a number pasted as +20 (10) 1234-5678 becomes +201012345678.

Implementation

String mreNormalizePhoneInput(String input) {
  final out = StringBuffer();
  final trimmed = input.trimLeft();

  for (var i = 0; i < trimmed.length; i++) {
    final unit = trimmed.codeUnitAt(i);
    final digit = _asciiDigit(unit);
    if (digit != null) {
      out.writeCharCode(digit);
    } else if (unit == 0x2B && out.isEmpty) {
      out.write('+');
    }
  }
  return out.toString();
}