[프로그래머스] 신규 아이디 추천 ( javascript)

728x90
반응형

1. 내 풀이 

function solution(new_id) {

//     1단계
    new_id=new_id.toLowerCase();
//     2단계
    for(let i=0;i<new_id.length;i+=1){
        if(!(new_id[i]>='a' && new_id[i]<='z') && new_id[i]!='-' && new_id[i]!='_' && new_id[i]!='.' && !(new_id[i]>='1' && new_id[i]<='9')){
            new_id=new_id.substring(0,i)+new_id.substring(i+1);
            i-=1;
        }
    }
//     3단계
    
    while(true){
        let pass=true;
        for(let i=0;i<new_id.length-1;i+=1){
            if(new_id[i]==='.' && new_id[i+1]==='.'){
                new_id=new_id.substring(0,i)+new_id.substring(i+1);
                pass=false;
            }
        }
        if(pass)break;
    }
    if(new_id[0]==='.'){
        new_id=new_id.substring(1);
    }
    if(new_id[new_id.length-1]==='.'){
        new_id=new_id.substring(0,new_id.length-1);
    }
    if(new_id===''){
        new_id='a';
    }
    if(new_id.length>=16){
        new_id=new_id.substring(0,15);
        if(new_id[new_id.length-1]==='.'){
        new_id=new_id.substring(0,new_id.length-1);
    }
    }
    while(new_id.length<=2){
        new_id+=new_id[new_id.length-1];
    }
    return new_id;
}

2. 정규 표현식 풀이 

 

function solution(new_id) {
    const answer=new_id.toLowerCase()
    .replace(/[^\w-_.]/g,'')
    .replace(/\.+/g,".")
    .replace(/^\.|\.$/g,'')
    .replace(/^$/,'a')
    .slice(0,15)
    .replace(/\.$/,'');
    return answer.length>2? answer:answer+answer.charAt(answer.length-1).repeat(3-answer.length);
}

728x90
반응형
TAGS.

Comments