CSS&JS/Frontend Mini Challenge

[FMC]03.Telephone Formatter

arancia_ 2023. 4. 10. 16:22

데모 사이트 : https://ohikmyeong.github.io/frontend-mini-challenges/telephone-formatter/

 

telephone formatter

 

ohikmyeong.github.io

 

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>telephone formatter</title>
    <link rel="stylesheet" type="text/css" href="./../common/reset.css"/>
    <script src="./../common/common.js" defer></script>
    <script src="./main.js" type="module"></script>
</head>
<body>
<main>
    <input id="ipt-tel" type="text" placeholder="mobile number" style="width:90%; max-width:400px;"/>
    <p style="font-size:14px;margin-top:1rem;">+(000)-1234-5678</p>
</main>
</body>
</html>
cs

JS

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
32
33
34
35
36
37
38
39
40
41
42
43
44
class TelephoneFormatter{
    constructor(){
        this.$ipt = document.getElementById('ipt-tel');
        this.init();
    }//constructor
 
    init(){
        //change는 focus out 부터 발생함
        //그래서 input 이벤트로 해줘야함
        this.$ipt.addEventListener('input',e =>{
            const str = this.get_number_only(e.target.value);
            if(!str) return;
            
            if(str.length < 4){
                this.$ipt.value = str;
            }else if(str.length > 3 && str.length <= 7){
                this.$ipt.value = this.str_formatter_fst(str) + str.substring(3);
            }else{
                this.$ipt.value = this.str_formatter_fst(str) + str.substring(3,7+ '-' + str.substring(7,11);
            }
        });
    }//init
    
    /**
     * input을 2개써야하나 했는데 integer만 가져오는 방법이 있었음
     * @param {String}str
     * @url https://github.com/sadanandpai/frontend-mini-challenges/blob/main/src/mc/telephone-formatter/index.js
     * @url https://regexr.com/5mhou
     * @url https://velog.io/@slaslaya/String.prototype.match%EC%99%80-String.prototype.matchAll-%EB%B9%84%EA%B5%90-%EC%BA%A1%EC%B2%98-%EA%B7%B8%EB%A3%B9Capture-Groups%EC%9D%B4%EB%9E%80
     */
    get_number_only(str){
        return str?.match(/\d+/g)?.join('');
    }//get_number_only
 
    /** 
     * 앞에 3자리를 +(000)- 으로 반환해줌 
     * @param {String}str
     * */
    str_formatter_fst(str){
        return `+(${str.substring(0,3)})-`;
    }//str_formatter_fst
}//TelephoneFormatter
 
new TelephoneFormatter();
cs

 

  • string에서 숫자만 가져오는 방법 : str?.match(/\d+/g)?.join('')
  • 앞에 세글자만 +(nnn)- 으로 바꿔서 반환하는 방법 : `+(${str.substring(0,3)})-`

'CSS&JS > Frontend Mini Challenge' 카테고리의 다른 글

[FMC]05.Toast Popup  (0) 2023.06.13
[FMC]04.Light Dark Mode  (0) 2023.06.13
[FMC]02.Guess the Number  (0) 2023.04.10
[FMC]01.Counter  (0) 2023.02.22