DEV Community

Discussion on: how to fix

Collapse
 
mohammadaltaleb profile image
Mohammad Altaleb • Edited

You are reversing the characters of the whole string, then reversing the words. The if statement has no effect because you are checking the length of original string every time (not the words).

Try this:

function spinWords(str) {
  let words = str.split(" ");
  let result = [];

  for(let word of words) {
    let newWord = word.length >= 5 ? word.split("").reverse().join("") : word;
    result.push(newWord);
  }

  return result.join(" ");
}

spinWords("Hey fellow warriors");

or this:

function spinWords(str) {
  let words = str.split(" ");
  let result = [];

  for(let word of words) {
    if(word.length >= 5) {
      result.push(word.split("").reverse().join(""));
    } else {
      result.push(word);
    }
  }

  return result.join(" ");
}

spinWords("Hey fellow warriors");