Emmanuel Akinfulubi

JavaScriptString

Mask a credit card number in JavaScript

Intermediate · 4 min read

When a shop shows your saved card as ************1111, it is masking the number: hiding all but the last four digits so you can recognize the card without anyone reading it over your shoulder. The same idea hides phone numbers, account numbers and API keys on screen.

In this tutorial you will write mask in one line using slice and padStart. Then you will find a bug that hides nothing at all when you ask to keep zero digits, and fix it. You should know what slice and length do on a string. Negative numbers in slice are explained below.

Two tools: slice with a negative number, and padStart

slice(-4) counts from the end. A negative start means "this many characters from the end", so slice(-4) gives the last four characters.

JavaScript

console.log('4111111111111111'.slice(-4)); // '1111'

padStart(width, fill) adds the fill character to the front of a string until it reaches the width you ask for. If the string is already that long, it is returned as it is.

JavaScript

console.log('1111'.padStart(8, '*')); // '****1111'
console.log('1111'.padStart(2, '*')); // '1111'

Put the two together and you have a mask: keep the tail, then pad it back 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 step by step.

46 Mask a card number

fair

Hide all but the last four digits of a card number, keeping the width the same. Then ask for zero visible digits and see what you get.

Stuck? Three hints, smallest first
  1. 1. Take the tail you want to keep, then padStart it back to the original length.
  2. 2. Strip spaces before masking, or the mask comes out too wide.
  3. 3. slice(-0) is slice(0), because -0 === 0.

Step 1: keep the last four

Step 1

const digits = '4111111111111111';
const tail = digits.slice(-4);
console.log(tail); // '1111'

This is the part we want to show.

Step 2: pad back to the full width

Step 2

const mask = (digits, keep = 4) => digits.slice(-keep).padStart(digits.length, '*');
console.log(mask('4111111111111111'));        // '************1111'
console.log(mask('4111111111111111').length); // 16
console.log(mask('987654', 2));               // '****54'

keep = 4 is a default parameter: if the caller doesn't pass a second argument, keep is 4. Padding to digits.length makes the masked string exactly as wide as the real one, so it lines up in a list.

Step 3: a short number

Step 3

const mask = (digits, keep = 4) => digits.slice(-keep).padStart(digits.length, '*');
console.log(mask('123')); // '123'

'123'.slice(-4) can't take four characters from a string of three, so it returns all three, and padStart(3) adds nothing. Whether that is acceptable depends on your data, but it is predictable.

Step 4: ask to keep zero, the natural wrong turn

Now ask for no visible digits. You would expect all stars:

Step 4

const mask = (digits, keep = 4) => digits.slice(-keep).padStart(digits.length, '*');
console.log(mask('9876', 0)); // '9876', nothing hidden
console.log(-0 === 0);        // true

Every digit is visible. Here is why. With keep set to 0, slice(-keep) is slice(-0). In JavaScript, -0 is equal to 0, so slice(-0) is the same as slice(0): "start at the beginning". It returns the whole string, and the mask hides nothing.

No error, no warning. A keep value that comes from a setting, or from a subtraction that happens to reach zero, quietly shows the full number.

Step 5: fix it with an explicit check

Step 5

const maskSafe = (digits, keep = 4) =>
  (keep <= 0 ? '' : digits.slice(-keep)).padStart(digits.length, '*');
console.log(maskSafe('9876', 0));             // '****'
console.log(maskSafe('4111111111111111'));    // '************1111'

The ? : is the conditional operator: "if keep <= 0, use an empty tail, otherwise slice". An empty string padded to full width is all stars. Normal calls behave exactly as before.

Step 6: spaces in the input

Card numbers are often typed with spaces. Those spaces count towards the length:

Step 6

const mask = (digits, keep = 4) => digits.slice(-keep).padStart(digits.length, '*');
console.log(mask('4111 1111 1111 1111').length);                  // 19
console.log(mask('4111 1111 1111 1111'.replace(/\s/g, '')));     // '************1111'

The spaced number is 19 characters, so the mask comes out 19 wide, with the spaces turned into stars. Removing whitespace first with replace(/\s/g, '') gives the 16-character mask you wanted. \s matches any whitespace and g means every match.

A word on safety

Masking only changes what is shown. If your code holds the full card number in memory to mask it, the full number is still there. Real payment systems avoid keeping it at all and store only the last four digits. Treat this exercise as string practice, not as security.

The full solution

The panel has mask and maskSafe and prints the normal mask, keeping two, the keep-zero bug, the fix and the spaced input. Press Run and look at the keep-zero line, then read the checks underneath.

The answer

const mask = (digits, keep = 4) => digits.slice(-keep).padStart(digits.length, '*');

// slice(-0) is slice(0), so keep = 0 returns the WHOLE string. An explicit
// check is the only fix.
const maskSafe = (digits, keep = 4) =>
  (keep <= 0 ? '' : digits.slice(-keep)).padStart(digits.length, '*');

console.log('mask     :', mask('4111111111111111'));
console.log('keep 2   :', mask('987654', 2));
console.log('keep 0   :', mask('9876', 0), '<- nothing hidden at all');
console.log('keep 0, fixed :', maskSafe('9876', 0));
console.log('with spaces   :', mask('4111 1111 1111 1111'), '<- padded to 19, not 16');

Output


      
10 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 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('all but the last four are hidden', mask('4111111111111111'), '************1111');
test('the width is unchanged', mask('4111111111111111').length, 16);
test('keeping two instead of four', mask('987654', 2), '****54');
test('a number shorter than the tail is returned whole', mask('123'), '123');
test('keeping none does NOT hide everything, because slice(-0) is slice(0)', mask('9876', 0), '9876');
test('an explicit check is the fix', maskSafe('9876', 0), '****');
test('spaces in the input inflate the mask', mask('4111 1111 1111 1111').length, 19);
test('so strip them first', mask('4111 1111 1111 1111'.replace(/\s/g, '')), '************1111');
test('the visible tail is exactly the last four characters', mask('4111111111111111').slice(-4), '1111');
test('and nothing but stars comes before it', /^[*]+$/.test(mask('4111111111111111').slice(0, -4)), true);

slice(-0) is the trap, and it is the same -0 === 0 fact that made at(-0) return the first character in exercise 3. A "keep" count that could arrive as zero — from a configuration value, or from a subtraction — turns a masking function into an identity function, silently, in production.

Masking is a display concern. The value being masked here is a full card number held in memory, which is what PCI rules are about; the safe pattern is to store only the last four and never have the rest to mask. Treat this as string work, not as a security control.

Common mistakes

  • Trusting slice(-keep) when keep can be 0. slice(-0) returns the whole string. Check for zero first.
  • Masking with spaces still in the number. The mask comes out too wide. Strip whitespace before masking.
  • Padding with padEnd. That puts the stars after the digits. The stars go in front, so use padStart.

Try it yourself

  1. Make maskSafe throw a clear error when keep is not a whole number, and test it with maskSafe('9876', 1.5).
  2. Write maskEmail('ada@example.com') that keeps the first letter and the domain: 'a**@example.com'.
  3. Mask a spaced card number but keep its spaces in place, so you get '**** **** **** 1111'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.