티스토리 뷰

반응형

 



 

 

 

 

입력폼에서 전화번호 입력했을 때 하이픈을 자동으로 기입하고 싶을 때가 있다.

 

입력할 때 계산해서 하이픈 자동 변환 함수를 만들어서 사용해 봤다.

 

function addHyphenToPhoneNumber(phoneNumberInput) {
    const phoneNumber = phoneNumberInput.value;
    const length = phoneNumber.length;

    if(length >= 9) {
        let numbers = phoneNumber.replace(/[^0-9]/g, "")
        			.replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`);
        phoneNumberInput.value = numbers;
    }
}


const phoneInput = document.getElementById("phone");
phoneInput.addEventListener("input", () => {
	addHyphenToPhoneNumber(phoneInput);
});
<input type="text" name="phone" id="phone" >

 

 

위와 같이 사용해서

 

최소 9자리에서 11자리가 입력 됐을 때 하이픈이 자동으로 생성되게 처리하였다.

 

 

// 정규식 설명

.replace(/[^0-9]/g, "") // 숫자 제외한 문자 제거

.replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`) // 숫자 $1(2,3)-$2(3,4)-$3(4) 자리로 치환

 

 

 

 

 



 

 

 

 

 

 

 

 

 

 

 

[JS] 전화번호 자동 하이픈(-) 정규식

첫 번째 코드 const phone = '01012345678'; phone.replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`); // '010-1234-5678' 00-000-0000 또는 000-0000-0000 전화번호를 (2, 3) - (3, 4) - (4) 자리에 숫자 그룹을 지어 묶어줍니다. replace()

gurtn.tistory.com

 

 

 

 

 

 

반응형
댓글
반응형
최근에 올라온 글
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Total
Today
Yesterday