Search code examples
stringdartuppercase

capitalize first letter of string and first letter after dot


I have this string for example:

String text = 'hello. i am Gabriele. i am 21 years old!';

I would like the first letter to be capitalized and every first letter after the "." To be capitalized.

Anyone know how I can do? Thanks :)


Solution

  • The first letter and all the first letters after the dot will be uppercase.

    void main() {
      String text = 'hello. i am Gabriele. i am 21 years old!';
      String capitalized = capitalizeAfterDot(text);
    
      print(capitalized); // Hello. I am Gabriele. I am 21 years old!
    }
    
    String capitalizeAfterDot(String text) {
      final split = text.replaceAll(RegExp(r'\.\s+'), ' #').split(' ');
      String result = split.reduce((a, b) {
        if (b.startsWith('#')) {
          return a + b.replaceRange(0, 2, '. ' + b[1].toUpperCase());
        }
        return a + ' ' + b;
      });
    
      return result.replaceRange(0, 1, result[0].toUpperCase());
    }
    

    OR

    String capitalizeAll(String text) {
      return text.replaceAllMapped(RegExp(r'\.\s+[a-z]|^[a-z]'), (m) {
        final String match = m[0] ?? '';
        return match.toUpperCase();
      });
    }