Dart String Extensions

Commonly needed String extension methods for Flutter apps — capitalization, truncation, validation, and more.

#extensions#string#utils
dart
1extension StringX on String {
2 // Capitalize first letter
3 String get capitalize => isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
4 
5 // Title case every word
6 String get titleCase => split(' ').map((w) => w.capitalize).join(' ');
7 
8 // Truncate with ellipsis
9 String truncate(int maxLength, {String ellipsis = '...'}) {
10 if (length <= maxLength) return this;
11 return '${substring(0, maxLength - ellipsis.length)}$ellipsis';
12 }
13 
14 // Validation
15 bool get isValidEmail {
16 return RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$').hasMatch(this);
17 }
18 
19 bool get isValidUrl {
20 return RegExp(r'^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b').hasMatch(this);
21 }
22 
23 bool get isValidPhone => RegExp(r'^[+]?[0-9]{8,15}$').hasMatch(replaceAll(' ', ''));
24 
25 // Parsing
26 int? get toIntOrNull => int.tryParse(this);
27 double? get toDoubleOrNull => double.tryParse(this);
28 
29 // Utils
30 String get removeHtml => replaceAll(RegExp('<[^>]*>'), '');
31 String get toSlug => toLowerCase().trim().replaceAll(RegExp(r'[^a-z0-9]+'), '-');
32 bool get isBlank => trim().isEmpty;
33 bool get isNotBlank => !isBlank;
34 String get nullIfBlank => isBlank ? '' : this; // or return null with nullable
35}
36 
37extension NullableStringX on String? {
38 bool get isNullOrEmpty => this == null || this!.isEmpty;
39 bool get isNullOrBlank => this == null || this!.isBlank;
40 String get orEmpty => this ?? '';
41}
42 
43// Usage
44'hello world'.titleCase; // 'Hello World'
45'bilal@bidev.site'.isValidEmail; // true
46'Flutter is awesome!'.truncate(14); // 'Flutter is ...'
47' '.isBlank; // true