DEV Community

Meera Menon
Meera Menon

Posted on

1

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"

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️