Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/src/string.dart
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ extension StringIsLatin1Extension on String {
}
}

extension StringOnlyDigitsExtension on String {
/// Returns a string containing only ASCII digit characters from this string.
String get onlyDigits => replaceAll(RegExp(r'[^0-9]'), '');
}

extension StringReversedExtension on String {
/// Returns a new string with characters in reversed order.
String get reversed {
Expand Down Expand Up @@ -160,6 +165,11 @@ extension StringIsDoubleExtension on String {
bool get isDouble => toDoubleOrNull() != null;
}

extension StringIsNumericExtension on String {
/// Returns `true` if the string can be parsed as a number.
bool get isNumeric => toDoubleOrNull() != null;
}

extension StringToDoubleExtension on String {
/// Parses the string as a [double] number and returns the result.
double toDouble() => double.parse(this);
Expand Down
18 changes: 18 additions & 0 deletions test/string_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ void main() {
expect('ő'.isLatin1, false);
});

test('.onlyDigits', () {
expect(''.onlyDigits, '');
expect('abc'.onlyDigits, '');
expect('123'.onlyDigits, '123');
expect('Phone: +1 (555) 123-4567'.onlyDigits, '15551234567');
expect('a1 b2-c3'.onlyDigits, '123');
});

test('.isBlank', () {
expect(' '.isBlank, true);
expect(' . '.isBlank, false);
Expand Down Expand Up @@ -132,6 +140,16 @@ void main() {
expect('123456789.987654321'.isDouble, true);
});

test('.isNumeric', () {
expect(''.isNumeric, false);
expect('a'.isNumeric, false);
expect('12abc'.isNumeric, false);
expect('1'.isNumeric, true);
expect('-42'.isNumeric, true);
expect('1.0'.isNumeric, true);
expect('123456789.987654321'.isNumeric, true);
});

test('.toDouble()', () {
expect('0'.toDouble(), 0.0);
expect('0.0'.toDouble(), 0.0);
Expand Down