How would you mask all but the last four digits of a card number in JavaScript?
Take the last four characters with slice(-4) and pad the front back to the original length with padStart(length, '*'). padStart and padEnd fill a string to a target length from the left or right.
Explain it simply
Payment apps show cards like "**** 5678" so nobody sees the full number. You only need the last four digits and a way to fill the rest.
slice(-4) takes the last four characters. padStart(targetLength, fillString) then adds the fill character on the left until the string reaches the target length. Using the original length as the target restores the original width, with stars where the hidden digits were.
padEnd does the same on the right, useful for aligning text columns in plain output.
Example
function maskCard(number) {
const digits = String(number);
return digits.slice(-4).padStart(digits.length, "*");
}
console.log(maskCard("1234567812345678")); // Output: ************5678
console.log(maskCard("1234567812345678").length); // Output: 16
console.log("7".padStart(3, "0")); // Output: 007
console.log("Name".padEnd(8, ".") + "Fee"); // Output: Name....FeeWhat to say in the interview
"I slice the last four characters and use padStart to restore the original length with asterisks. I take the input as a string, because a long card number as a Number can lose precision. Real masking should also happen on the server."
Common mistakes
- Storing a card number in a Number type. Long values lose digits.
- Masking only in the UI while the full value is still sent to the page.