Open abdelhakim-sahifa opened 2 months ago
String titleCase(String text) {
titleCase
takes a String
parameter called text
and returns a String
. final List<String> excludeWords = ['and', 'or', 'the', 'to', 'of', 'for', 'in', 'on', 'at', 'by', 'with', 'as'];
excludeWords
is a list of small words that should not be capitalized unless they are the first or last word in the input string. final List<String> words = text.trim().split(RegExp(r'\s+'));
text
string is trimmed to remove any leading or trailing whitespace.split
method is used with a regular expression RegExp(r'\s+')
to divide the string into a list of words based on one or more whitespace characters. String capitalize(String word) {
if (word.length <= 2 || word.toUpperCase() == word) return word;
return word[0].toUpperCase() + word.substring(1).toLowerCase();
}
capitalize
function takes a String
parameter called word
. 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();
}
}
for
loop iterates over each word in the words
list.-
), it splits the word into parts, capitalizes each part, and then joins them back with hyphens.excludeWords
list, it is capitalized.excludeWords
list, it is converted to lowercase. return words.join(' ');
}
This function converts a given string into title case while handling special cases such as hyphenated words and small words that should not be capitalized unless they are the first or last word in the string.
Here's an enhanced version of the
titleCase
function with additional features: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.