전화번호 포맷팅 — replace 는 매치된 부분만 바꾸고 나머지는 뒤에 그대로 남긴다. 그래서 그룹 자릿수 합이 길이와 같아야 한다1
function formatPhoneNumber(phoneNumber) {
const cleaned = phoneNumber.replace(/\D/g, '')
if (cleaned.length === 11) {
return cleaned.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3')
} else if (cleaned.length === 10 && cleaned.startsWith('02')) {
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '$1-$2-$3')
} else if (cleaned.length === 10) {
return cleaned.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')
} else if (cleaned.length === 9 && cleaned.startsWith('02')) {
return cleaned.replace(/(\d{2})(\d{3})(\d{4})/, '$1-$2-$3')
}
return 'Invalid phone number'
}
formatPhoneNumber('01012341234') // 010-1234-1234
formatPhoneNumber('021234567') // 02-123-4567
formatPhoneNumber('0212345678') // 02-1234-5678
Footnotes
-
String.prototype.replace() - MDN: “returns a new string with one, some, or all matches of a
patternreplaced by areplacement.” ↩
거리 만km 포맷팅 — toFixed(1) 은 반올림하고 0 까지 채운 문자열을 준다(100000 → 10.0만km)1
function formatToManKm(distance: number): string {
const manKm = (distance / 10000).toFixed(1)
return `${manKm}만km`
}
formatToManKm(104335) // "10.4만km"
Footnotes
-
Number.prototype.toFixed() - MDN: “The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.” ↩