코테연습

37.Simple Pig Latin

hxunz 2022. 4. 11. 21:28

Description:

Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.

Examples

pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldway !

 


function pigIt(str){
  const words = str.split(' ');
  let w = '';
  
  for (i=0; i < words.length; i++) {
    if (words[i].match(/[a-z]/i)) {
      w += words[i].substring(1) + words[i].substring(0, 1) + 'ay '
    } else {
      w += words[i]
    }
  }
  const result = w.trim();
  
  return result;
}

먼저 주어진 문장에서 단어들을 쪼개서 배열로 만들어주었다.

const words = str.split(' ');

그 다음에는 반복문을 돌면서 스트링인지 아닌지에 대한 예외처리를 해주었고 

if (words[i].match(/[a-z]/i))

해당 배열의 요소가 스트링이라면 단어의 첫번째 위치에 잇는 문자열을 그 단어의 맨뒤로 옮긴다음에 ay 를 더해주었다.

w += words[i].substring(1) + words[i].substring(0, 1) + 'ay '

해당 배열의 요소가 스트링이 아닌 특수문자가 오는경우에는 그대로 w에 더해지도록 해주었다.

else {
  w += words[i]
}

그 다음에는 ay 를 추가할때 뒤에 공백을 넣어주었기 때문에 맨 앞이랑 뒤에 공백 제거를 해주는 trim()을 사용해주었다.

const result = w.trim();