Mask a phone number in JavaScript
Beginner · 3 min read
Banking apps, delivery apps and account pages often show a phone or card number like *******4567. You can still recognize your own number from the last few digits, but someone looking over your shoulder can't read the rest. This is called masking.
In this tutorial you will write a function called mask that hides everything except the last four characters, keeps the length the same, and never shows a short number in full by accident. You need to know what a string and a function are. We will use slice and padStart, and both are explained below.
Two tools you need
slice with a negative number counts from the end of a string. slice(-4) gives the last four characters:
console.log('08031234567'.slice(-4)); // 4567
padStart(width, char) adds characters to the front of a string until it is width long:
console.log('4567'.padStart(11, '*')); // *******4567
Put those two together and you have the whole idea: take the tail you want to show, then pad it back out to the original length with stars.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
107 Mask a phone number
easyShow a stored phone number as *******4567: last four digits visible, everything else hidden, and the length unchanged. Then make sure a short number is not accidentally revealed in full.
Stuck? Three hints, smallest first
- 1.
slice(-4)gives the visible tail;padStartcan fill the rest with stars. - 2. If the number is no longer than the visible window, hide all of it.
- 3.
slice(-0)is not "the last nothing" — check what it actually does.
Step 1: the core of the mask
const text = '08031234567';
const masked = text.slice(-4).padStart(text.length, '*');
console.log(masked); // *******4567
console.log(masked.length); // 11
text.length is 11, so the four visible digits get seven stars in front. Keeping the length the same matters: a table of masked numbers stays lined up, and nobody can tell how long a number is from the stars changing.
Step 2: wrap it in a function
function mask(value, keep = 4, char = '*') {
const text = String(value);
return text.slice(-keep).padStart(text.length, char);
}
console.log(mask('5399123456781234')); // ************1234
console.log(mask('08031234567', 3, 'x')); // xxxxxxxx567
keep is how many characters to show and char is the mask character. Both have defaults, so mask(number) does the usual thing.
Step 3: a short number leaks
What if the number is only four characters long?
function mask(value, keep = 4, char = '*') {
const text = String(value);
return text.slice(-keep).padStart(text.length, char);
}
console.log(mask('0803')); // 0803
The last four characters are the whole thing, so nothing gets hidden. A mask that shows everything isn't a mask. The rule should be: if the text is no longer than the part you'd show, hide all of it.
Step 4: the strange case of keep = 0
Asking to keep nothing should hide everything. Look at what slice does with it:
console.log('08031234567'.slice(-0)); // 08031234567
-0 is just 0 to slice, and slice(0) means "from the start to the end". So the request for the most secrecy shows the full number. This is exactly the kind of edge case worth testing.
Step 5: guard both cases
function mask(value, keep = 4, char = '*') {
const text = String(value);
if (keep <= 0 || text.length <= keep) return char.repeat(text.length);
return text.slice(-keep).padStart(text.length, char);
}
console.log(mask('08031234567')); // *******4567
console.log(mask('0803')); // ****
console.log(mask('08031234567', 0)); // ***********
console.log(mask('') === ''); // true
char.repeat(n) makes a string of n copies of char. The guard at the top catches both the short number and keep = 0, and returns all stars at the right length. An empty string gives ''.length, which is 0, so you get back an empty string.
String(value) also lets the function take a number. Notice what happens to the leading zero, though:
console.log(String(8031234567)); // 8031234567
A phone number stored as a number has already lost its leading zero. Store phone numbers as text.
Masking is only for display
The mask changes what is shown on screen, not what is stored. If the full number reaches the browser, anyone who opens the developer tools can still see it. If a value must stay private, mask it on the server before sending it.
The full solution
The answer panel has the finished mask and checks a phone number, a card number, a short number, an empty string, keep = 0, a numeric argument and a custom mask character. Press Run to see the output.
function mask(value, keep = 4, char = '*') {
const text = String(value);
if (keep <= 0 || text.length <= keep) return char.repeat(text.length);
return text.slice(-keep).padStart(text.length, char);
}
console.log(mask('08031234567'), mask('5399123456781234'), mask('0803'));
console.log('slice(-0) returns:', '08031234567'.slice(-0));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the last four digits stay readable', mask('08031234567'), '*******4567');
test('the length is unchanged, so the layout does not move', mask('08031234567').length, 11);
test('a card number masks the same way', mask('5399123456781234'), '************1234');
test('a number no longer than the window is hidden completely', mask('0803'), '****');
test('empty text stays empty', mask(''), '');
test('keep 0 hides everything', mask('08031234567', 0), '***********');
test('and without that guard slice(-0) would show it all', '08031234567'.slice(-0), '08031234567');
test('a numeric argument survives because of String()', mask(8031234567), '******4567');
test('the mask character is a parameter', mask('08031234567', 3, 'x'), 'xxxxxxxx567');
slice(-keep).padStart(text.length, char) is the whole trick: take the tail you want to show, then pad it back out to the original width. That keeps the mask the same length as the number, so a table of masked numbers stays aligned and nobody learns how long the value was from the column shifting.
keep = 0 is the trap, and it is -0. Negative zero equals zero, so slice(-0) is slice(0) — the entire string, printed in the clear, in the one case where you asked for maximum secrecy. The guard turns that into all stars. Masking is presentation, not protection: the full value is still in memory and in the response that carried it, so if it must not reach the browser, mask it on the server. Money and identifiers are also why String(value) is there — a phone number held as a number has already lost its leading zero.
Common mistakes
- Building the stars from a fixed count.
'*******' + text.slice(-4)is only right for 11-digit numbers. Pad totext.lengthinstead. - Not testing short input. A four-digit value comes back in full unless you guard it.
- Trusting
slice(-keep)withkeep = 0.slice(-0)returns the whole string.
Try it yourself
- Write
maskEmail('chinwe@example.com')that shows the first letter and the domain:'c*****@example.com'. - Change
maskso it also keeps the first three characters, giving'080****4567'. - Group a masked card number into blocks of four:
'**** **** **** 1234'.