핸드폰 번호 일부 마스킹크 작업 (정규식 이용)

by 조쉬 posted Jun 19, 2015
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄
<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Document</title>
 </head>
 <body>
  <script>
    
    /** 
     * 핸드폰번호 마스크처리(010-11**-*111)
     * 정규식 이용. 
     */

    function hpFormatHiddenByRegx(hp) {
        var pattern = /^(\d{3})-?(\d{1,2})\d{2}-?\d(\d{3})$/;
        var result = "";
        if(!hp) return result;

        var match = pattern.exec(hp);
        if(match) {
            result = match[1]+"-"+match[2]+"**-*"+match[3];
        } else {
            result = "***";
        }
        return result;
    }
    
    /** 
     * 핸드폰번호 마스크처리(010-11**-*111)
     * 정규식 이용. 작업을 최소화 (치환 방식)
     */

    function hpFormatHiddenByRegx2(hp) {
        var pattern = /^(\d{3})-?(\d{1,2})\d{2}-?\d(\d{3})$/;
        var result = "";
        if(!hp) return result;

        if(pattern.test(hp)) {
            result = sampleHpData[i].replace(pattern, '$1-$2**-*$3');
        } else {
            result = "***";
        }
        return result;
    }

    //문서 출력용 함수
    function print(str1, str2) {
        document.write(str1+" : "+str2 +"<br/>");
        console.log(str1+" : "+str2);
    }

    //테스트/=====================================================================================
    
    var sampleHpData = ["01012345678" , "0101234567" , "010123451234512345",
                        "010-1234-1234", "010-123-1234", "123"];

    for( i in sampleHpData) {
        //var tmp = sampleHpData[i].replace(/^(\d{3})-?(\d{1,2})\d{2}-?\d(\d{3})$/, '$1-$2**-*$3');
        var tmp = hpFormatHiddenByRegx(sampleHpData[i]);
        print(sampleHpData[i],tmp);
    }
    print("-","-");
    for( i in sampleHpData) {
        var tmp = hpFormatHiddenByRegx2(sampleHpData[i]);
        print(sampleHpData[i],tmp);
    }

  </script>
 </body>
</html>