Mask String

Mask string, mobile number etc. Usefull while logging sensitive content.

commit 1dc50f8 · authored · 1 min read

/// <summary>
/// Mask the string.
/// </summary>
/// <param name="value">String that need to be masked</param>
/// <param name="startIndex">zero index indicating mask start position</param>
/// <param name="mask">mask that need to be applied, eg. ***</param>
/// <returns>Usage: "123456789".Mask(3, "****") => "123****89"</returns>
public static string Mask(this string value, int startIndex, string mask)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
var result = value;
var starLength = mask.Length;
if (value.Length < startIndex) return result;
result = value.Insert(startIndex, mask);
result = result.Length >= (startIndex + (starLength * 2)) ? result.Remove(startIndex + starLength, starLength) : result.Remove(startIndex + starLength, result.Length - (startIndex + starLength));
return result;
}

Tests

"123456789".Mask(3, "****").Should().Be("123****89");
"123456789".Mask(3, "****---").Should().Be("123****---");

Reference

local graph · open full graph

"Mask String" is connected to the topics C# and related to 7 other entries. NDepend - The Best-in-class Static Code Analyzer for Dotnet NDepend - The Best-in-class… C# - Convert DateTime to Long and Vice Versa C# - Convert DateTime to Lo… C# - Get Last N characters from a string C# - Get Last N characters … C# - Get Web.Config Connection String in a Class Library C# - Get Web.Config Connect… Using AutoMapper in a .NET Core Class Library Using AutoMapper in a .NET … Check if string is Arabic - C# Check if string is Arabic -… Truncate String Without Word Break Truncate String Without Wor… C# #c-sharp Mask String

comments

loading discussion…