Skip to content

Enhanced Version Of titleCase #1

Description

@abdelhakim-sahifa

Here's an enhanced version of the titleCase function with additional features:

  1. Excludes short words from capitalization: Words like "and", "or", "the" won't be capitalized unless they're the first or last word.
  2. Handles acronyms: Words in all caps will remain in all caps.
  3. Deals with hyphenated words: Both parts of hyphenated words will be capitalized.
String titleCase(String text) {
  final List<String> excludeWords = ['and', 'or', 'the', 'to', 'of', 'for', 'in', 'on', 'at', 'by', 'with', 'as'];
  final List<String> words = text.trim().split(RegExp(r'\s+'));

  String capitalize(String word) {
    if (word.length <= 2 || word.toUpperCase() == word) return word;
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  }

  for (int i = 0; i < words.length; i++) {
    if (words[i].contains('-')) {
      words[i] = words[i]
          .split('-')
          .map((part) => capitalize(part))
          .join('-');
    } else if (i == 0 || i == words.length - 1 || !excludeWords.contains(words[i].toLowerCase())) {
      words[i] = capitalize(words[i]);
    } else {
      words[i] = words[i].toLowerCase();
    }
  }

  return words.join(' ');
}

This enhanced version of titleCase takes care of more specific capitalization rules, making the output more refined and accurate for a variety of text inputs.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions