JAVASCRIPT
Mask Sensitive Data (e.g., Credit Card Numbers) for Display
Learn to securely mask sensitive information like credit card numbers in a string using regular expressions, displaying only the last few digits for privacy and security.
function maskSensitiveDigits(inputString, visibleDigits = 4) {
if (typeof inputString !== 'string') {
inputString = String(inputString);
}
// Matches any digit that is NOT among the last 'visibleDigits' digits in a sequence.
// E.g., for visibleDigits=4, it matches digits that have 4 digits following them.
const pattern = new RegExp(`\\d(?=\\d{${visibleDigits}})`,'g');
return inputString.replace(pattern, '*');
}
const ccNumber1 = "1234567890123456";
const maskedCc1 = maskSensitiveDigits(ccNumber1); // "************3456"
const accountNumber = "987654321";
const maskedAccount = maskSensitiveDigits(accountNumber, 3); // "******321"
const shortId = "12345";
const maskedShort = maskSensitiveDigits(shortId); // "12345" (no change as less than 5 digits)
How it works: The `maskSensitiveDigits` function takes a string and a `visibleDigits` count (defaulting to 4). It constructs a regular expression `\d(?=\d{${visibleDigits}})` using a positive lookahead. This regex matches any digit `\d` that is immediately followed by exactly `visibleDigits` more digits. By replacing these matched digits with an asterisk (`*`), it effectively masks all but the final `visibleDigits` in any sequence of digits long enough to have more than `visibleDigits`. This provides a flexible way to obscure sensitive numeric data.