'Writing function that returns string but with all five or more letters reversed JS
first time posting. I'm writing a function in js that reverses words with more than 5 characters in a given string. It works, but I think it is adding extra "space" strings that it doesn't need if the string inputted is only one word. I know I have too many variables and there is a way better way to do this. I'm pretty new to this, but anything helps. Thanks!
const exString = "Hey fellow warriors"
function spinWords(string){
let newWord = string.split(' ');
let fiveWord = "";
let lessWord = "";
for(i=0; i<newWord.length;i++){
if(newWord[i].length >=5){
fiveWord += newWord[i].split('').reverse() + ' ';
}
else{
lessWord += newWord[i]
}
}
newFiveWord = fiveWord.replace(/,/g,'');
return lessWord + ' ' + newFiveWord
}
console.log(spinWords(exString));
Solution 1:[1]
const spinWords = str => str
.split(' ')
.map(word => word.length >= 5
? [...word].reverse().join('')
: word)
.join(' ')
console.log(spinWords("Hey fellow warriors"))
- Turn the string into an array of words
- Modify each word. If 5+ letters:
[..word]turns the string into an array of letters ('hi'>['h', 'i']). Then reverse the array, and turn the letters back into one string. - Undo step one by turning the array into one string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
