DEV Community

Meera Menon
Meera Menon

Posted on

how to fix

i want to only reverse word strings that are more than 5 letters but in my result even the three letter words are getting reversed, how do i fix this ?

Top comments (2)

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");
Collapse
 
dharshann profile image
Dharshan Bharathuru
def spinWords(sentence)
  sentence.split(' ').map { |word| word.length > 5 ? word.reverse : word }.join(' ')
end

spinWords('hi hello welcome to ruby learning')
# "hi hello emoclew to ruby gninrael"