본문 바로가기
코딩테스트 연습/Javascript

Pig Latin | match(), regexp, replace(), concat()

by 홍차23 2020. 12. 30.

Problem>

Pig Latin is a way of altering English Words. The rules are as follows:

- If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add "ay" to it.

- If a word begins with a vowel, just add "way" at the end.

 

Solution>

function pigIt(str) {
    let regex = /^[^aeiou]+/;
    let consonant = str.match(regex);
    return consonant !== null
        ? str
            .replace(regex, "")
            .concat(consonant)
            .concat("ay")
        : str.concat("way");
};

console.log(pigIt('glove'));

 

Review>

 

str.match(regexp)

: 문자열이 정규식과 매치되는 부분을 검색하여, 일치하는 전체 문자열을 첫번째 요소로 포함하는 array 반환. 일치하는 것이 없으면 null 반환.

 

1) regex 변수에 첫부분에 있는 자음을 검색하는 정규표현식 정의

2) consonant 변수에 regex에 해당하는 부분을 담는다.

3) consonant 가 null 이 아닌 경우(단어가 자음으로 시작한 경우) 

3-1) regex 에 해당하는 첫부분 "" 으로 replace()

3-2) 남은 str 에 consonant 변수 에 담긴 자음 concat()

3-3) "ay" 문자열 concat()

4) 단어가 모음으로 시작한 경우 "way" 문자열 concat()

 

댓글