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'
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'
To mask the first N characters of a string with a symbol, you would need 3 ingredients:
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'
I made it robust to handle also:
N = -1. It currently has no effect.