Home > front end >  Capitalize First Letter Of Each Name after Hyphen "-" and Space " "
Capitalize First Letter Of Each Name after Hyphen "-" and Space " "

Time:01-25

I'm currently using this String extension to Capitalize the letter of each word in a textField :

"happy sunshine" .toTitleCase() gives "Happy Sunshine"

extension StringExtension on String {
  String toTitleCase() => replaceAll(RegExp('  '), ' ')
      .split(' ')
      .map((str) => str.toCapitalized())
      .join(' ');
  String toCapitalized() =>
      length > 0 ? '${this[0].toUpperCase()}${substring(1).toLowerCase()}' : '';
}

but I'd also like to Capitalize letters that come after a hyphen - with the same toTitleCase method

ex : "very-happy sunshine" .toTitleCase() would give "Very-Happy Sunshine"


Currently .toTitleCase() gives "Very-happy Sunshine" : (

CodePudding user response:

I am sure a wizard with expert knowledge in regular expression can do this better but I think this solution solves your problem:

void main() {
  print('happy sunshine'.toTitleCase()); // Happy Sunshine
  print('very-happy sunshine'.toTitleCase()); // Very-Happy Sunshine
}

extension StringExtension on String {
  String toTitleCase() => replaceAllMapped(
      RegExp(r'(?<= |-|^).'), (match) => match[0]!.toUpperCase());
}

If you call the method a lot of times, you might consider having the RegExp as a cached value like:

extension StringExtension on String {
  static final RegExp _toTitleCaseRegExp = RegExp(r'(?<= |-|^).');

  String toTitleCase() =>
      replaceAllMapped(_toTitleCaseRegExp, (match) => match[0]!.toUpperCase());
}

CodePudding user response:

You can tweak your code as well. But I've used the same thing somewhere in my project so you can do something like this as well.

Working: First I'm creating an empty array looping through each character in a particular string and checking if space (" ") and hyphen ("-") are current_position - 1 then I'm making current_position to uppercase.

String capitalize(String s) {
  String result = "";
  for (int i = 0; i < s.length; i  ) {
    if (i == 0) {
      result  = s[i].toUpperCase();
    } else if (s[i - 1] == " ") {
      result  = s[i].toUpperCase();
    } else if (s[i - 1] == "-") {
      result  = s[i].toUpperCase();
    } else {
      result  = s[i];
    }
  }
  return result;
}
  •  Tags:  
  • Related