문제
프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.
입출력 예
phone_number | return |
---|---|
"01033334444" | "***4444" |
"027778888" | "*8888" |
풀이
repeat()
, slice()
함수를 사용하자.
String.prototype.repeat()
repeat()
메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.
- RangeError: 반복 횟수는 양의 정수여야 함.
- RangeError: 반복 횟수는 무한대보다 작아야 하며, 최대 문자열 크기를 넘어선 안됨.
'abc'.repeat(-1); // RangeError 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) 'abc'.repeat(1/0); // RangeError ({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // 'abcabc' (repeat() is a generic method)
그래서
'*'.repeat(phone_number.length - 4)
코드를 통해 phone_number길이에서 4만큼 뺀 숫자만큼 *을 반복하는 것을 알 수 있다!
String.prototype.slice()
slice()
메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.const str = 'The quick brown fox jumps over the lazy dog.'; console.log(str.slice(31)); // expected output: "the lazy dog." console.log(str.slice(4, 19)); // expected output: "quick brown fox" console.log(str.slice(-4)); // expected output: "dog." console.log(str.slice(-9, -5)); // expected output: "lazy"
phone_number.slice(-4)
코드를 통해 phone_number에서 마지막 4자리를 구할 수 있다!
즉, '*'.repeat(phone_number.length - 4)
+ phone_number.slice(-4)
를 통해 결과를 구할 수 있다!
전체 코드
function solution(phone_number) {
var answer = '*'.repeat(phone_number.length - 4) + phone_number.slice(-4);
return answer;
}
출처 [프로그래머스] 핸드폰 번호 가리기 - Javascript
출처 Javascript 핸드폰 번호 가리기