JSFiddle - React, Tailwind, and code Playground
by chucknelson
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/1.7.48/libphonenumber-js.min.js"></script>
<input id="phone" type="text">
<h3 id="phone-raw">phone-raw</h3>
JavaScript
const phoneInput = document.getElementById("phone")
const phoneRaw = document.getElementById("phone-raw")
phoneInput.addEventListener('keyup', function(event) {
phoneRaw.innerHTML = libphonenumber.parseIncompletePhoneNumber(this.value)
let newValue = new libphonenumber.AsYouType('US').input(this.value)
if (newValue === this.value) {
const newValueFormatted = libphonenumber.formatIncompletePhoneNumber(newValue, 'US')
if (newValueFormatted.indexOf(event.target.value) === 0) {
// Trim the last digit (or plus sign).
newValue = newValue.slice(0, -1)
}
}
this.value = newValue
})