I made a component to format phone number from XXXXXXXXXX
to '(XXX) XXX-XXXX'
here is my code
function formatPhoneNumber(phone) {
const area = phone.slice(0, 3);
const first = phone.slice(3, 6);
const second = phone.slice(6, 10);
let formattedTelephoneNumber = phone;
if (phone.length >= 1) {
formattedTelephoneNumber = `(${formattedTelephoneNumber}`;
}
if (phone.length >= 4) {
formattedTelephoneNumber = `(${area}) ${first}`;
}
if (phone.length >= 7) {
formattedTelephoneNumber = `(${area}) ${first}-${second}`;
}
return formattedTelephoneNumber;
}
function getRawPhoneNumber(inputValue) {
return [...inputValue].filter((char) => /\d/.test(char)).join("");
}
export default function App() {
const [value, setValue] = useState("");
const handleInputChange = (e) => {
const phoneNumber = getRawPhoneNumber(e.target.value);
const formatted = formatPhoneNumber(phoneNumber);
setValue(formatted);
};
return (
<div className="App">
<input value={value} onChange={handleInputChange} />
</div>
);
}
It works ok but when you are typing in the middle of a string - either add an extra number or delete one number, the cursor will jump to the end.
Does anyone know how to fix it?
here is a live demo you can play with https://codesandbox.io/s/phone-number-format-x4nnk?file=/src/App.js