69 lines
2.5 KiB
TypeScript
69 lines
2.5 KiB
TypeScript
|
|
/**
|
|
* 전화번호에 - 처리
|
|
* @param value '-'없는 전화번호
|
|
* @returns
|
|
*/
|
|
export const formatKoreanPhoneNumber = (value: string) => {
|
|
const digits = value.replace(/\D/g, "").slice(0, 11); // 숫자만 추출하고 최대 11자리까지만 사용
|
|
if (!digits) return ""; // 입력이 비어 있으면 빈 문자열 반환
|
|
|
|
if (/^1\d{0,7}$/.test(digits)) { // 15xx/16xx/18xx 같은 대표번호 패턴
|
|
if (digits.length <= 4) return digits; // 아직 뒷자리가 부족하면 원문 유지
|
|
return `${digits.slice(0, 4)}-${digits.slice(4, 8)}`; // xxxx-xxxx
|
|
}
|
|
|
|
if (digits.startsWith("02")) { // 서울 지역번호(02)
|
|
const rest = digits.slice(2); // 국번/가입자번호 구간
|
|
if (!rest) return "02"; // 02만 입력된 상태
|
|
if (rest.length <= 3) return `02-${rest}`; // 02-xxx
|
|
if (rest.length <= 7) return `02-${rest.slice(0, 3)}-${rest.slice(3)}`; // 02-xxx-xxxx
|
|
return `02-${rest.slice(0, 4)}-${rest.slice(4, 8)}`; // 02-xxxx-xxxx
|
|
}
|
|
|
|
if (digits.startsWith("0")) { // 02 제외 일반 지역번호/휴대폰(010 포함)
|
|
const area = digits.slice(0, 3); // 앞 3자리 식별자
|
|
const rest = digits.slice(3); // 나머지 번호
|
|
if (!rest) return area; // 식별자만 입력된 상태
|
|
if (rest.length <= 3) return `${area}-${rest}`; // 0xx-xxx
|
|
if (rest.length <= 7) return `${area}-${rest.slice(0, 3)}-${rest.slice(3)}`; // 0xx-xxx-xxxx
|
|
return `${area}-${rest.slice(0, 4)}-${rest.slice(4, 8)}`; // 0xx-xxxx-xxxx
|
|
}
|
|
|
|
if (digits.length <= 4) return digits; // 예외 입력: 앞 4자리까지
|
|
if (digits.length <= 8) return `${digits.slice(0, 4)}-${digits.slice(4)}`; // xxxx-xxxx
|
|
return `${digits.slice(0, 4)}-${digits.slice(4, 8)}-${digits.slice(8, 11)}`; // xxxx-xxxx-xxx
|
|
};
|
|
|
|
/**
|
|
* 숫자 문자열에 형식 문자열을 적용합니다.
|
|
* @param format 하이픈 위치를 포함한 형식 문자열. 예: 000-00-00000-0000
|
|
* @param value 형식을 적용할 원본 값
|
|
* @returns 형식이 적용된 문자열
|
|
*/
|
|
export const formatValueByPattern = (format: string, value: string) => {
|
|
const digits = value.replace(/\D/g, "");
|
|
if (!digits) return "";
|
|
|
|
let digitIndex = 0;
|
|
let result = "";
|
|
|
|
for (const char of format) {
|
|
if (char === "0") {
|
|
if (digitIndex >= digits.length) break;
|
|
result += digits[digitIndex];
|
|
digitIndex += 1;
|
|
continue;
|
|
}
|
|
|
|
if (digitIndex >= digits.length) break;
|
|
result += char;
|
|
}
|
|
|
|
if (digitIndex < digits.length) {
|
|
result += digits.slice(digitIndex);
|
|
}
|
|
|
|
return result;
|
|
};
|