onlyNumbers method

String onlyNumbers([
  1. bool removeSpaces = false
])

Extracts only digit characters, removing everything else.

The removeSpaces parameter is accepted for API consistency but currently unused.

Example:

'(123)-456-7890'.onlyNumbers()             // '1234567890'
'abc123def456'.onlyNumbers()               // '123456'
'no digits here'.onlyNumbers()             // ''

Implementation

String onlyNumbers([bool removeSpaces = false]) {
  String result = replaceAll(RegExp(r'[^0-9]'), '');
  return removeSpaces ? result.replaceAll(RegExp(r'\s+'), '') : result;
}