모법답안
const solution = (new_id) => {
const id = new_id
.toLowerCase()
.replace(/[^\w\d-_.]/g, '')
.replace(/\.{2,}/g, '.')
.replace(/^\.|\.$/g, '')
.padEnd(1, 'a')
.slice(0, 15)
.replace(/^\.|\.$/g, '')
return id.padEnd(3, id[id.length-1])
}
내답안
function solution(new_id) {
var answer = '';
var special_pattern = /[\~\!\@#$%\^\&\*\(\)\[\]=+\{\}:\?,<>\/]/gi;
var dot_pattern=/\.+/g;
new_id=new_id.toLowerCase();
new_id=new_id.replace(special_pattern,"");
new_id=new_id.replace(dot_pattern,".");
console.log(new_id)
if(new_id[0]==="."){
new_id= new_id.substring(1,new_id.length);
}
console.log(new_id)
if(new_id[new_id.length-1]==="."){
new_id= new_id.substring(0,new_id.length-1);
}
console.log(new_id)
if(new_id.length===0){
new_id="a"
}
console.log(new_id)
if(new_id.length>=16){
new_id= new_id.substr(0,15);
console.log(new_id,"df")
if(new_id[new_id.length-1]===".")
new_id=new_id.substring(0,new_id.length-1);
}
console.log(new_id)
if(new_id.length<=2){
const lastChar=new_id[new_id.length-1];
for(let i= new_id.length;i<3;i++){
new_id+=lastChar;
}
}
console.log(new_id)
answer=new_id
return answer;
}
정규표현식을 잘몰라서 한땀한땀 열심히 쳤는데 padEnd 함수라는 것의 존재와 함수체이닝..
앞 뒤 .체크를 정규식으로 할 수 있었다는 것에서 무릎을 탁치고 머리를 책상에 박아버리고 말았다.