AsYouType formats a number one character at a time, so a user typing 4155552671 sees (415) 555-2671 appear as they go. This guide shows how to use it, with a live demo, and the one pitfall that trips people up.
Basic usage
Create an AsYouType instance with a default country, then call input with the full string each time. It returns the formatted version.
import { AsYouType } from 'libphonenumber-js'
new AsYouType('US').input('4155552671')
// '(415) 555-2671'
new AsYouType().input('+44207946')
// '+44 20 7946'Format in an input handler
Create a new instance on each change and pass in the whole value. Do not reuse one instance for edits, because it remembers the previous input.
input.addEventListener('input', () => {
input.value = new AsYouType('US').input(input.value)
})Read the result as you type
The instance can tell you what it has understood so far, for example the country and whether the number is complete enough to be valid.
const ayt = new AsYouType('US')
ayt.input('415555')
ayt.getNumber()?.country // 'US'
ayt.getNumber()?.isValid() // false until completeWhat it cannot do
AsYouType was designed for a numeric keypad, so it accepts digits and a leading plus sign. It does not support typing an extension: the characters after the number are ignored, and the library's documentation suggests a separate field for the extension. new AsYouType('US').input('2133734253 ext 12') returns (213) 373-4253.
Use reset() to clear an instance, and getTemplate() to see the pattern it is using. For (213) 373 it returns (xxx) xxx.
The pitfall: deleting characters
If you rewrite input.value on every keystroke, the cursor jumps to the end and deleting a bracket or space can feel stuck. For a production field, set the value only when it differs and restore the cursor position, or use a component that handles this for you.
Format a finished number instead
For a number that is already complete, format it with the Formatter tool or with phone.formatNational() and phone.formatInternational().