diff --git a/framework/src/Volo.Abp.Core/System/AbpStringExtensions.cs b/framework/src/Volo.Abp.Core/System/AbpStringExtensions.cs index 3fb7573858..a7cf7c763e 100644 --- a/framework/src/Volo.Abp.Core/System/AbpStringExtensions.cs +++ b/framework/src/Volo.Abp.Core/System/AbpStringExtensions.cs @@ -192,6 +192,19 @@ namespace System return str; } + public static string ReplaceFirst(this string str, string search, string replace, StringComparison comparisonType = StringComparison.Ordinal) + { + Check.NotNull(str, nameof(str)); + + var pos = str.IndexOf(search, comparisonType); + if (pos < 0) + { + return str; + } + + return str.Substring(0, pos) + replace + str.Substring(pos + search.Length); + } + /// /// Gets a substring of a string from end of the string. /// diff --git a/framework/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs b/framework/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs index 503abf7156..8a818a75cb 100644 --- a/framework/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs @@ -187,6 +187,14 @@ namespace System "Https://abp.io".RemovePreFix(StringComparison.OrdinalIgnoreCase, "https://").ShouldBe("abp.io"); } + [Fact] + public void ReplaceFirst_Tests() + { + "Test string".ReplaceFirst("s", "X").ShouldBe("TeXt string"); + "Test test test".ReplaceFirst("test", "XX").ShouldBe("Test XX test"); + "Test test test".ReplaceFirst("test", "XX", StringComparison.OrdinalIgnoreCase).ShouldBe("XX test test"); + } + [Fact] public void ToEnum_Test() {