c-sharp

Mask String

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

Edson Frainlar
Edson FrainlarSeptember 12, 2020 · 1 min read · Last Updated:
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;
12
13 var result = value;
14 var starLength = mask.Length;
15
16 if (value.Length < startIndex) return result;
17
18 result = value.Insert(startIndex, mask);
19
20 result = result.Length >= (startIndex + (starLength * 2)) ? result.Remove(startIndex + starLength, starLength) : result.Remove(startIndex + starLength, result.Length - (startIndex + starLength));
21
22 return result;
23}

Tests

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

Reference

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Edson Frainlar

Written byEdson Frainlar
Mission-driven Full-stack Developer with a passion for developing KTern, Dev Collaboration, and teaching. Curious to explore Quantum Information and Computing.
Connect

Is this page helpful?

Related VideosView All

Don't Use AutoMapper in C#! Do THIS Instead!

How slow is MediatR really?

C# Language Highlights: Properties