Web Platform Feature of the Week logo

Web Platform Feature of the Week

Subscribe
Archives
July 14, 2025

String.repeat() - Web Platform Feature of the Week

Diving into the lesser-known JavaScript function 'String.repeat' with a credit card use case!

Welcome to the first edition of the Web Platform Feature of the Week newsletter. Thank you so much for subscribing.

This week, I thought I would start with a JavaScript function that might not be so widely known.

String.repeat();

You can find all the details for String.repeat on MDN Web Docs.

I must be honest that it took me a bit of thinking to come up with a real-life use case, which is always my aim when demonstrating a web platform feature. With that said, I believe I did come up with a rather common use case for it.

The code

function getDisplayString(cardType, visibleDigits) {
  const padChar = "*";
  const cardTypes = {
    visa: 16,
    mastercard: 16,
    discover: 16,
    diners: 14,
    jcb: 16,
    amex: 15,
    unionPay: 19
  };
  const totalLength = cardTypes[cardType] || 16;
  const repeatCount = totalLength - visibleDigits.length;

  return `${padChar.repeat(repeatCount)}${visibleDigits}`;
}

You can experiment with the above code on Codepen.

What does it do?

We have a function named, getDisplayString that takes two parameters namely, cardType and visibleDigits. We use cardType to determine how many total characters the card number contains, and visibleDigits are the digits we can show. We do not want the full credit card number floating around in our frontend code after all 😜

This means that we have two strings of variable length. After getting our total length, we determine our repeat count by subtracting the number of visible characters from the total length.

All that remains is to return our display string.

return `${padChar.repeat(repeatCount)}${visibleDigits}`;

This line says, construct a new string that repeats the asterisk character, for example, twelve times, and then append the visible characters that were passed to the function. For example:

console.log(`VISA: ${getDisplayString("visa", "5567")}`);

This will output: VISA: ************5567

Watch on YouTube

Conclusion

Easy peasy, am I right? I hope you found this interesting or useful and that you perhaps even learned something new.

Can you think of other use cases? Have you used the repeat function before? Let me know in the comments on YouTube!

Until next week, keep rocking the free web ✌️


Do you like short one-topic emails like this one? You do?? Then you should check out the inspiration for this newsletter, One Tip a Week by Nick Taylor.

Don't miss what's next. Subscribe to Web Platform Feature of the Week:
GitHub Website Bluesky LinkedIn
Powered by Buttondown, the easiest way to start and grow your newsletter.