Devlog/Web

[Angular] 국내 연락처 변환용 Pipe

Damien.Lee 2020. 12. 8. 19:08
반응형
 

 

일반 전화번호부터 지역국번 및 전국대표번호까지 입력된 숫자에 맞춰 ' - ' 하이픈( hyphen )이 적용된 포멧으로 변환시켜줍니다.

 

사용방법

1. Module 초기화.

// 필자가 전역으로 사용하는 모듈임. ***** 해당 모듈은 app.module.ts 에 import 됩니다.
// app.module.ts 에 ContactPipe를 선언 (declarations) 하셔도 됩니다.
// shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// ...
import { ContactPipe } from 'src/sys/contact.pipe';



@NgModule({
  declarations: [
  	//...
    ContactPipe
  ],
  imports: [
    //...
    CommonModule
  ],
  exports: [
  	// 모듈에 선언된 pipe를 외부에서 사용가능하도록 하기 위해 exports에 선언해둔다.
    ContactPipe
  ]
})
export class SharedModule { }

 

// contact.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'phone' })
export class ContactPipe implements PipeTransform {
  static format(num: string, displayType: 'normal'|'secret' = 'normal'): string {
    num = num.replace(/[^0-9]/g, '');
    let formatNum = '';
    if (num.length < 4) {
      return num;
    } else if (num.length < 8) {
      // 지역번호 제외 집전화 : @@@ - @@@@
      formatNum = displayType === 'secret' ? num.replace(/(\d{3})(\d{4})/, '***-$2') : num.replace(/(\d{3})(\d{4})/, '$1-$2');
    } else if (num.length < 9) {
      // 단축 연락처. Ex)1544-...., 1588-.... : @@@@ - @@@@
      formatNum = displayType === 'secret' ? num.replace(/(\d{4})(\d{4})/, '****-$2') : num.replace(/(\d{4})(\d{4})/, '$1-$2');
    } else if (num.length < 11) {
      if (num.startsWith('02')) {
        if (num.length < 10) {
          // 서울 일반 전화번호 : 02 - @@@ - @@@@
          formatNum = displayType === 'secret' ? num.replace(/02(\d{3})(\d{4})/, '02-***-$2') : num.replace(/02(\d{3})(\d{4})/, '02-$1-$2');
        } else {
          // 서울 국번 : 02 - @@@@ - @@@@
          formatNum = displayType === 'secret' ? num.replace(/02(\d{4})(\d{4})/, '02-****-$2') : num.replace(/02(\d{4})(\d{4})/, '02-$1-$2');
        }
      } else {
        // 지역번호 포함된 집전화 / 01x 구번호 사용자 가운데 3자리. @@@ - @@@ - @@@@
        formatNum = displayType === 'secret' ? num.replace(/(\d{3})(\d{3})(\d{4})/, '$1-***-$3') : num.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
      }
    } else {
      // 핸드폰 번호, 인터넷 전화. : @@@ - @@@@ - @@@@
      formatNum = displayType === 'secret' ? num.replace(/(\d{3})(\d{4})(\d{4})/, '$1-***-$3') : num.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
    }
    return formatNum;
  }

  constructor() { }
  public transform(num: string, displayType: 'normal'|'secret' = 'normal' ): string {
    return ContactPipe.format(num, displayType);
  }
}

 

 

2. Component HTML에 작성.

아래와 같이, phone 뒤에 'secret' 을 추가하면, 연락처 중간번호를 별표(숨김)처리하여 표시됩니다.

기본값은 'normal' 이며, 입력하지 않아도 일반연락처 폼으로 표시 됩니다.

<div>{{ '010-1234-1234' | phone:'secret' }}</div> <!-- 010-****-1234 -->
<div>{{ '010-1234-1234' | phone:'normal' }}</div> <!-- 010-1234-1234 -->
<div>{{ '010-1234-1234' | phone }}</div> <!-- 010-1234-1234 -->

 

참고자료

- gist 링크

반응형