0

I want to mask a string in ReactJS, as in replacing the first N characters with the * symbol. But I want N to be variable.

Example:

const item = '1234567890'
const masked = masked(item, 6);
console.log(masked); // '******7890'
1
  • 1
    I guess the question is where is the value coming from in the first place and should it be masked there? E.g if it's a from a network request, someone could inspect the network tab and see it come back in a response making your client side masking redundant Commented Jul 23, 2021 at 13:05

2 Answers 2

1

If I get you correctly you could just try this:

const item = '1234588567890';

// How many letters you want to leave readable at the end
const cutoff = 4;
const formattedItem = '*'.repeat(item.length - cutoff) + item.slice(-cutoff);

console.log(formattedItem)

Sign up to request clarification or add additional context in comments.

Comments

1

To mask the first N characters of a string with a symbol, you would need 3 ingredients:

  • the length of the the string
  • the integer count N of first characters to mask (hide)
  • the a calculation of the length of (a) the masked part, (b) the shown part
  • a masking symbol (usually a single character)

A reusable function would be implemented like this:

function masked(str, n) {
    var maskingSymbol = '*';  // could make this a parameter

     // n might be longer than string
    var lengthToMask = Math.min(str.length, n);
    var lengthToShow = Math.max(0, str.length-n)

    // build parts    
    var maskedPart = ''
    if (lengthToMask > 0) { // repeat count must be positive
         maskedPart= maskingSymbol.repeat(lengthToMask);
    }
    var shownPart = '';
    if (lengthToShow > 0) { // slice count must be non zero
         shownPart =  str.slice(-lengthToShow);
    }
    
    return maskedPart + shownPart;
}

const item = '1234567890'
const maskedItem = masked(item, 6);

console.log(maskedItem); // '******7890'

// further tests for edge-cases
console.log("N = 0", masked(item, 0)); // '1234567890'
console.log("N = 9", masked(item, 9)); // '*********0'
console.log("N = 10", masked(item, 10)); // '**********'
console.log("N = 11", masked(item, 11)); // max 10 masked: '**********'
console.log("N = -1", masked(item, -1)); // negative not implemented, so nothing masked: '1234567890'

Robustness to handle variable input

I made it robust to handle also:

  • strings that are smaller than the masking-count N
  • negative masking-count like N = -1. It currently has no effect.

Extension points

  • negative masking-count N might mask the trailing characters. So it masks the last N characters
  • the masking-symbol (single character) can be passed in as parameter
  • or even: the masking-symbol could also span multiple characters like `/'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.