Algorithm/JavaScript

[프로그래머스 Lv. 1] 핸드폰 번호 가리기

dbfl9911 2023. 10. 20. 19:05

[문제 설명]

프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.

 

[입출력 예]

phone_number return
"01033334444" "*******4444"
"027778888" "*****8888"

 

[풀이]

- 1. 마지막 네자리 숫자 구하기

=> slice 함수 이용(slice(시작인덱스, 종료인덱스))

- 2. 뒷 4자리 제외한 나머지 숫자 '*'으로 바꿔주기 

=> repeat 함수 이용 (repeat(반복할 횟수))

- 3. concat 함수 이용해 위 두개 합치기

function solution(phone_number) {
    const lastNum = phone_number.slice(phone_number.length-4, phone_number.length); // 마지막 네자리 숫자
    const num = '*'.repeat(phone_number.length - 4); // 마지막 네자리 숫자 전까지 숫자
    const answer = num.concat(lastNum);
    return answer;
}