How to hide part of a string
Short answer
Take the last four characters and fill the rest of the length with stars:
const card = '4111111111111111';
const masked = card.slice(-4).padStart(card.length, '*');
console.log(masked);Output:
************1111Leave the first letter of the name and the domain, and hide the rest:
const email = 'anna.smith@example.com';
const [name, domain] = email.split('@');
const masked = name[0] + '*'.repeat(name.length - 1) + '@' + domain;
console.log(masked);Output:
a*********@example.comCommon mistake
If the string is shorter than the visible part, repeat() gets a negative number and throws an error. Guard against short strings:
const mask = (text, visible = 4) =>
text.length <= visible ? text : '*'.repeat(text.length - visible) + text.slice(-visible);
console.log(mask('123'));
console.log(mask('123456789'));Output:
123
*****6789Functions used in this recipe
- String.prototype.slice — Returns part of a string.
- String.prototype.padStart — Pads a string on the left to a given length.
- String.prototype.repeat — Repeats a string a given number of times.