this can be used to projects that you need to format user's phone based these formats:
- (DDD) 12345-1234
- (DDD) 1234-1234
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>phone input formatter</title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
</head> | |
<body> | |
<input id="phone-input" maxLength="15" /> | |
<script src="index.js"></script> | |
</body> | |
</html> |
function formatNumber(phone){ | |
phone = phone.slice(0, 15); | |
//111111111 (9) --> 11111 1111 | |
//11111111 (8) --> 1111 1111 | |
const phoneBody = phone.includes('(') | |
? phone.substring(5).replace('-', '') | |
: phone.substring(2); | |
const firstPartSize = phoneBody.length % 2 === 0 ? 4 : 5; | |
const splitPartsRegex = new RegExp(`(\\d{${firstPartSize}})`); | |
return phone | |
.replace(/\D/g, '') //remove letters | |
.replace(/(\d{2})/, '($1) ') // put DDD around parenteses | |
.replace(splitPartsRegex, '$1-'); // add a "-" after 5 or 4 digits (depending on the phone size) | |
} | |
const input = document.querySelector('input'); | |
input.onchange = (event) => { | |
const phone = event.target.value; | |
if(!phone) return; | |
const formattedPhone = formatNumber(phone); | |
input.value = formattedPhone; | |
}; |