format.creditCard
v0.1.0 latestFormat a credit card number with brand-aware digit grouping per ISO/IEC 7812 BIN prefix detection.
Format a credit card number with brand-aware digit grouping per ISO/IEC 7812 BIN prefix detection.
Signature
function creditCard(input: string, opt?: CreditCardFormatOptions): string | null
Type Definitions:
CreditCardFormatOptions— interface
Problem
Credit card numbers are stored as raw digit strings but must be displayed with brand-specific grouping (Visa: 4-4-4-4, Amex: 4-6-5). Manual 4-digit chunking ignores Amex and Diners patterns. Display masking for payment UIs requires replacing all but the last 4 digits with bullets.
How It Works
Strips existing separators, detects card brand from BIN prefix using a regex table (Visa, Amex, Mastercard, Diners, JCB, Discover, UnionPay), applies brand-specific grouping. Optionally masks all but the last 4 digits with '•' (bullet) before grouping. Returns null for invalid inputs outside the 12-19 digit range.
Boundaries
- Does not validate Luhn checksum — formatting only.
- Returns null for empty, non-digit, or cards outside 12-19 digit range.
- Throws TypeError for non-string input.
Replaces
Common boilerplate this function replaces:
digits.replace(/(\d{4})(?=\d)/g, '$1 ')
Examples
format.creditCard("4111111111111111"); // "4111 1111 1111 1111"
format.creditCard("378282246310005"); // "3782 822463 10005"
format.creditCard("4111111111111111", { mask: true }); // "•••• •••• •••• 1111"
format.creditCard("4111111111111111", { separator: "-" }); // "4111-1111-1111-1111"
format.creditCard(""); // null
Standards
Caveats
- Brand detection covers 7 major networks (Visa, Amex, Mastercard, Diners, JCB, Discover, UnionPay); unrecognized BINs default to 4-4-4-4 grouping.
- mask: true uses the bullet character '•' (U+2022), not an asterisk — consistent with payment UI conventions.
FAQ
How to format a credit card number with spaces in JavaScript?
format.creditCard('4111111111111111') returns '4111 1111 1111 1111' — auto-detects Visa and applies 4-4-4-4 grouping.
How to format an Amex card number differently from Visa?
The function auto-detects Amex from BIN prefix (34/37) and applies 4-6-5 grouping: format.creditCard('378282246310005') returns '3782 822463 10005'.
How to display a masked credit card number in a payment UI?
Use mask: true: format.creditCard('4111111111111111', { mask: true }) returns '•••• •••• •••• 1111'.
How to use dashes instead of spaces for credit card formatting?
Use separator: '-': format.creditCard('4111111111111111', { separator: '-' }) returns '4111-1111-1111-1111'.
Does credit card formatting validate the Luhn checksum?
No — format.creditCard() is display-only. It formats the number for human readability without validating the checksum.