c-sharp

Mask String

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

Abhith Rajan
Abhith RajanSeptember 12, 2020 · 1 min read · Last Updated:
/// <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

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


Abhith Rajan

Written byAbhith Rajan
Abhith Rajan is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related ArticlesView All

Related VideosView All

C# Project Management in VS Code [Pt 3] | C# and .NET Development in VS Code for Beginners

Installing VS Code and C# Dev Kit [Pt 2] | C# and .NET Development in VS Code for Beginners

What is VS Code and C# Dev Kit? [Pt 1] | C# and .NET Development in VS Code for Beginners