Skip to content

Commit 5fa5c65

Browse files
committed
✨ Add ReplaceValues extension method for string replacements
1 parent 30d1d37 commit 5fa5c65

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Drammer.Common.Tests/Extensions/StringExtensionsTests.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,4 +190,22 @@ public void ReplaceLastOccurrence_ReturnsReplacedText(string? input, string sear
190190
// assert
191191
result.Should().Be(expected);
192192
}
193+
194+
[Fact]
195+
public void ReplaceValues_ReturnsReplacedText()
196+
{
197+
// arrange
198+
const string Input = "abc def ghi";
199+
var replacements = new Dictionary<string, string>
200+
{
201+
{"def", "jkl"},
202+
{"ghi", "mno"}
203+
};
204+
205+
// act
206+
var result = Input.ReplaceValues(replacements);
207+
208+
// assert
209+
result.Should().Be("abc jkl mno");
210+
}
193211
}

src/Drammer.Common/Extensions/StringExtensions.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,28 @@ public static partial class StringExtensions
222222
return input.ToLower().Replace(uri.Host, tld.ToLower());
223223
}
224224

225+
/// <summary>
226+
/// Replaces values in a string.
227+
/// </summary>
228+
/// <param name="input"></param>
229+
/// <param name="replacements"></param>
230+
/// <returns></returns>
231+
[return: NotNullIfNotNull(nameof(input))]
232+
public static string? ReplaceValues(this string? input, IReadOnlyDictionary<string, string> replacements)
233+
{
234+
if (string.IsNullOrWhiteSpace(input) || replacements.IsNullOrEmpty())
235+
{
236+
return input;
237+
}
238+
239+
foreach(var (key, value) in replacements)
240+
{
241+
input = input.Replace(key, value);
242+
}
243+
244+
return input;
245+
}
246+
225247
/// <summary>
226248
/// Removes all HTML tags from a string.
227249
/// </summary>

0 commit comments

Comments
 (0)