출처: 2021 KAKAO BLIND RECRUITMENT
정규 표현식 연습하기 좋은 문제다.
원래는 불필요한 코드들이 더 많았는데 팀원들 제안 듣고 좀 더 간단하게 고쳤다.
원래는 문자열 길이가 3보다 작을 때, repeat()
메서드로 3에서 현재 문자열 길이 뺀 만큼
이전 문자열을 반복해주는 방식으로 구현했는데
코드 리뷰해준 분이 padEnd()
를 알려주셔서 수정해봤다. [MDN - padEnd()]
function solution(new_id) {
const answer = new_id
.toLowerCase() // 모든 문자를 소문자로 변환
.replace(/[^a-z\d-_.]/g, "") // 소문자, 숫자, -, _, .를 제외한 문자 제거
.replace(/[\.]{2,}/g, ".") // .가 2개 이상인 경우 하나만 남기고 제거
.replace(/^\.|\.$/g, "") // .로 시작하거나 .로 끝나는 경우 .를 제거
.slice(0, 15) // 15자리 숫자까지만 자르기
.replace(/\.$/, ""); // .로 끝나는 경우 .를 제거
if (answer.length >= 3) {
return answer;
} else if (answer.length === 0) {
return "aaa";
} else {
return answer.padEnd(3, answer[answer.length - 1]);
}
}
// 테스트 케이스
console.log(solution("...!@BaT#*..y.abcdefghijklm")); // "bat.y.abcdefghi"
console.log(solution("z-+.^.")); // "z--"
console.log(solution("=.=")); // "aaa"
console.log(solution("123_.def")); // "123_.def"
console.log(solution("abcdefghijklmn.p")); // "abcdefghijklmn"
console.log(solution("~!@#$%&*()=+[{]}:?,<>/")); // "aaa"
console.log(solution(".1.")); // "111"
'코딩테스트 문제풀이' 카테고리의 다른 글
[JavaScript/프로그래머스] 가장 긴 팰린드롬 (2) | 2021.09.13 |
---|---|
[JavaScript/프로그래머스] 문자열 압축 (0) | 2021.09.12 |