Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

************1111

Email

Leave 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.com

Common 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
*****6789

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.