1/// <summary>2/// Mask the string.3/// </summary>4/// <param name="value">String that need to be masked</param>5/// <param name="startIndex">zero index indicating mask start position</param>6/// <param name="mask">mask that need to be applied, eg. ***</param>7/// <returns>Usage: "123456789".Mask(3, "****") => "123****89"</returns>8public static string Mask(this string value, int startIndex, string mask)9{10 if (string.IsNullOrEmpty(value))11 return string.Empty;1213 var result = value;14 var starLength = mask.Length;1516 if (value.Length < startIndex) return result;1718 result = value.Insert(startIndex, mask);1920 result = result.Length >= (startIndex + (starLength * 2)) ? result.Remove(startIndex + starLength, starLength) : result.Remove(startIndex + starLength, result.Length - (startIndex + starLength));2122 return result;23}
Tests
1"123456789".Mask(3, "****").Should().Be("123****89");2"123456789".Mask(3, "****---").Should().Be("123****---");