From f42211c52436f2fefcfa405dd83fefa503b84bee Mon Sep 17 00:00:00 2001 From: Hisham Bin Ateya Date: Fri, 16 Sep 2022 22:11:06 +0300 Subject: [PATCH] Remove trailing hyphens count from a slug (#12433) --- .../Services/SlugService.cs | 20 ++++++++++++++++++- .../Tokens.Content/SlugServiceTests.cs | 10 ++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/OrchardCore.Modules/OrchardCore.Liquid/Services/SlugService.cs b/src/OrchardCore.Modules/OrchardCore.Liquid/Services/SlugService.cs index bbbb28483c8..0a37efbd2b9 100644 --- a/src/OrchardCore.Modules/OrchardCore.Liquid/Services/SlugService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Liquid/Services/SlugService.cs @@ -61,7 +61,25 @@ public string Slugify(string text) } } - return new string(slug.AsSpan()[..Math.Min(slug.Length, MaxLength)]).Normalize(NormalizationForm.FormC); + var length = Math.Min(slug.Length - GetTrailingHyphenCount(slug.AsSpan()), MaxLength); + + return new string(slug.AsSpan()[..length]).Normalize(NormalizationForm.FormC); + } + + private static int GetTrailingHyphenCount(ReadOnlySpan input) + { + var hyphenCount = 0; + for (var i = input.Length - 1; i >= 0; i--) + { + if (input[i] != Hyphen) + { + break; + } + + ++hyphenCount; + } + + return hyphenCount; } } } diff --git a/test/OrchardCore.Tests/Tokens.Content/SlugServiceTests.cs b/test/OrchardCore.Tests/Tokens.Content/SlugServiceTests.cs index 5a5c3364d10..a85243aebdf 100644 --- a/test/OrchardCore.Tests/Tokens.Content/SlugServiceTests.cs +++ b/test/OrchardCore.Tests/Tokens.Content/SlugServiceTests.cs @@ -36,6 +36,16 @@ public void ShouldChangeDotSymbolsToHyphans() Assert.Equal("a-d", slug); } + [Theory] + [InlineData("Smith, John B.")] + [InlineData("Smith, John B...")] + public void ShouldRemoveHyphansFromEnd(string input) + { + // Act + var slug = _slugService.Slugify(input); + Assert.Equal("smith-john-b", slug); + } + [Fact] public void ShouldMakeSureFunkycharactersAndHyphansOnlyReturnSingleHyphan() {