format.digits
v0.1.0 latestFormat a digit string according to a pattern where '#' represents a digit slot, per ECMA-262 String processing.
Format a digit string according to a pattern where '#' represents a digit slot, per ECMA-262 String processing.
Signature
function digits(input: string, pattern: string, opt?: DigitsFormatOptions): string | null
Type Definitions:
DigitsFormatOptions— interface
Problem
Raw digit strings (phone numbers, postal codes, ID numbers) need formatting with separators at specific positions. Each format has a different grouping pattern. Building one-off regex replacements for each format is repetitive and error-prone.
How It Works
Extracts characters from the input (digits only by default, or alphanumeric with allowAlpha: true), counts '#' slots in the pattern, and fills each '#' with the next extracted character. Literal characters in the pattern are passed through unchanged. Returns null if the input has fewer extracted characters than '#' slots.
Boundaries
- Returns null if extracted characters are fewer than '#' slots in the pattern.
- Throws TypeError for non-string input or pattern.
- Excess characters beyond the pattern's '#' slots are truncated.
Replaces
Common boilerplate this function replaces:
input.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3')
Examples
format.digits("1234567890", "(###) ###-####"); // "(123) 456-7890"
format.digits("123456", "##-##-##"); // "12-34-56"
format.digits("12", "###-####"); // null
format.digits("AB123", "##-###", { allowAlpha: true }); // "AB-123"
format.digits("12345678901234", "#### #### #### ##"); // "1234 5678 9012 34"
Standards
Caveats
- By default, only digit characters (0-9) are extracted from the input; non-digit characters are stripped. Use allowAlpha: true to retain alphabetic characters.
- The pattern is consumed left-to-right; there is no support for right-aligned or conditional patterns.
FAQ
How to format a phone number with a custom pattern in JavaScript?
format.digits('1234567890', '(###) ###-####') returns '(123) 456-7890' — fills '#' slots with digits from the input.
How to format a date string with dashes?
format.digits('20260301', '####-##-##') returns '2026-03-01' — the pattern defines the separator positions.
What happens if the input has fewer digits than the pattern requires?
Returns null — the function requires enough extracted characters to fill all '#' slots.
How to format mixed alphanumeric codes?
Use allowAlpha: true: format.digits('AB123', '##-###', { allowAlpha: true }) keeps both letters and digits.
How to format an arbitrary digit string with groups of 4?
Use a pattern with '#' groups: format.digits('1234567890', '#### #### ##') returns '1234 5678 90'.