Skip to content

Patterns ​

A pattern is a string where special characters mean "a … goes here", and everything else is shown as is.

Syntax ​

CharacterMeaning
9A digit
aA letter of any alphabet
*A letter or a digit
[ ... ]An optional part: filled completely or not at all
\The next character as is: \9 shows a nine
anything elseShown as is: brackets, spaces, dashes, +7
ts
mask('12345678', '(999) 999-99'); // '(123) 456-78'
mask('ab12', 'aa-99');            // 'ab-12'
mask('1230', '99:99[:99]');       // '12:30' — seconds are optional
mask('12', '\\9-99');             // '9-12'

How input is processed ​

  • Characters that don't fit a position are skipped: mask('a1b2', '99') → '12'.
  • Literals after the last typed character are not added — the user sees (123, not (123) .
  • Literals in the input match the pattern's literals, so formatting an already formatted value changes nothing.
  • Extra characters are dropped.

Custom tokens ​

A token is a regular expression for one character and, optionally, a transform:

ts
const serial = createMask({
  pattern: 'HH-HH-HH',
  tokens: { H: { pattern: /[0-9a-f]/i, transform: 'upper' } },
});

mask('a1b2c3', serial); // 'A1-B2-C3'

transform is 'upper', 'lower' or a (char) => string function.

Several patterns ​

An array of patterns: the first one that fits the whole input is used. List them from short to long:

ts
const code = createMask(['999-999', '9999-9999']);

mask('123456', code);   // '123-456'
mask('12345678', code); // '1234-5678'

Pattern function ​

When the pattern depends on the input — e.g. on the first digits of a card number:

ts
const cardMask = createMask({
  pattern: (input) => (/^3[47]/.test(input) ? '9999 999999 99999' : '9999 9999 9999 9999'),
});

Country code at the start ​

If a pattern starts with literals that look like input (+375, +998), they count as typed only when the input starts with + or has more digits than the pattern holds (a number pasted with the code). Otherwise the first digit isn't swallowed by the country code: mask('331234567', phone('by')) → +375 (33) 123-45-67.

See also ​