본문 바로가기
코테연습

20.Stop gninnipS My sdroW!

by hxunz 2022. 3. 30.

Description:

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"

 

function spinWords(string){
  const str = string.split(' ');
  
  for (i=0; i < str.length; i++) {
    if (str[i].length >= 5) {
      str[i] = str[i].split('').reverse().join('');
    }else {
      str[i];
    }
  }
  return str.join(' ')
}

먼저 주어진 문장을 공백 기준으로 잘라줘서 문장 내 단어들의 배열로 나타냈다.

const str = string.split(' ');
 
그 다음에는 for문을 이용해서 단어의 길이가 5 이상인 경우에는 단어들을 뒤집어줬고
if (str[i].length >= 5) {
str[i] = str[i].split('').reverse().join('');
 
단어의 길이가 5 미만인 경우에는 원래 단어 그대로 리턴하도록 해줬다. 
 
마지막에는 배열에 있는 단어들을 공백 기준으로 join() 해줬다.

'코테연습' 카테고리의 다른 글

22.Array.diff  (0) 2022.03.31
21.Sum of Digits / Digital Root  (0) 2022.03.31
19.Find the odd int  (0) 2022.03.29
18.Multiples of 3 or 5  (0) 2022.03.29
17.Find the next perfect square!  (0) 2022.03.27

댓글