0

Is there any easiest or built-in method in dart to change First Letter of every word to Uppercase

ex: system admin to System Admin

Favas Kv
  • 2,961
  • 2
  • 28
  • 38
  • 1
    Similar to https://stackoverflow.com/questions/29628989/how-to-capitalize-the-first-letter-of-a-string-in-dart – AlvaroSantisteban Sep 23 '19 at 13:02
  • Does this answer your question? [How to capitalize the first letter of a string in dart?](https://stackoverflow.com/questions/29628989/how-to-capitalize-the-first-letter-of-a-string-in-dart) – Mohammad Nazari Dec 22 '19 at 08:40

2 Answers2

3

You can use RegExp with String.replaceAllMapped

  var recase = RegExp(r'\b\w');
  var str = 'the quick brown fox jumps over the lazy dog';
  print(str.replaceAllMapped(recase, (match) => match.group(0).toUpperCase()));
  // The Quick Brown Fox Jumps Over The Lazy Dog
Spatz
  • 18,640
  • 7
  • 62
  • 66
  • 1
    The RegExp could be just `RegExP(r"\b\w")`. The `\b` match is zero-with, so it's not necessary to put it into a look-behind. It contains its own look-behind because its match depends on the previous character. – lrn Jul 26 '19 at 17:15
2

There is not built in method to do so, you can achieve that in many ways, one could be:

var string = 'system admin';
StringBuffer titleCase = StringBuffer();

string.split(' ')
  .forEach((sub) {
    if (sub.trim().isEmpty)
        return;

    titleCase
      ..write(sub[0].toUpperCase())
      ..write(sub.substring(1))
      ..write(' ');
  });

print(titleCase.toString()); //Prints "System Admin"

Or can use the recase package:

ReCase rc = ReCase('system admin');
(rc.titleCase); // Prints "System Admin"
Mattia
  • 5,909
  • 3
  • 26
  • 41