Favas Kv
Favas Kv

Reputation: 3099

Dart First Letter to Uppercase

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

Upvotes: -1

Views: 684

Answers (2)

Spatz
Spatz

Reputation: 20168

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

Upvotes: 3

Mattia
Mattia

Reputation: 6544

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"

Upvotes: 2

Related Questions