Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Humanizer.Tests/TransformersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,12 @@ public void TransformToSentenceCase(string input, string expectedOutput) =>
[InlineData("Title Case", "TITLE CASE")]
public void TransformToUpperCase(string input, string expectedOutput) =>
Assert.Equal(expectedOutput, input.Transform(To.UpperCase));

[Theory]
[InlineData("a great article", "A Great Article")]
[InlineData("yet another conjunction", "Yet Another Conjunction")]
[InlineData("by this preposition", "By This Preposition")]
[InlineData("NASA and the future", "NASA and the Future")]
public void TransformToTitleCase_FirstWordExceptions(string input, string expectedOutput) =>
Assert.Equal(expectedOutput, input.Transform(To.TitleCase));
}
13 changes: 11 additions & 2 deletions src/Humanizer/Transformer/ToTitleCase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public string Transform(string input) =>
#if NET7_0_OR_GREATER
[GeneratedRegex(WordPattern)]
private static partial Regex WordRegexGenerated();

private static Regex WordRegex() => WordRegexGenerated();
#else
private static readonly Regex WordRegexDefinition = new(WordPattern, RegexOptions.Compiled);
Expand All @@ -23,10 +23,19 @@ public string Transform(string input, CultureInfo culture)
var matches = WordRegex().Matches(input);
var builder = new StringBuilder(input);
var textInfo = culture.TextInfo;
var isFirstWord = true;

foreach (Match word in matches)
{
var value = word.Value;
if (AllCapitals(value) || IsArticleOrConjunctionOrPreposition(value))
var currentIsFirst = isFirstWord;
isFirstWord = false;

if (AllCapitals(value))
{
continue;
}
if (!currentIsFirst && IsArticleOrConjunctionOrPreposition(value))
{
continue;
}
Expand Down
Loading