Anm
Anm

Reputation: 806

Make a string titleCase

How can I make a string Title Case Like This? Other dart solutions did not work for me as some of the functions are not to be found in flutter.

Upvotes: -1

Views: 482

Answers (1)

Rohit Bhati
Rohit Bhati

Reputation: 496

This code will do the work:

extension CapTitleExtension on String {
  String get titleCapitalizeString => this.split(" ").map((str) => str[0].toUpperCase() + word.substring(1)).join(" ");
}

now use this with importing all Extension in any file.

import CapTitleExtension
            
final helloWorld = 'hello world'.titleCapitalizeString; // 'Hello World'

with function without Extension

String titleCase(String? text) {
  if (text == null) throw ArgumentError("string: $text");

  if (text.isEmpty) return text;

  return text
      .split(' ')
      .map((word) => word[0].toUpperCase() + word.substring(1))
      .join(' ');
}

Upvotes: 2

Related Questions