'How to reverse only words of a specific length in a string(JS)?

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. Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

 function spinWords(string){
    
    //splits string into words separated by a space
    var splitStringArray = string.split(" ");
    
    for (var i = 0; i < splitStringArray.length; i++) {
    //if the word is more than 5 chars, reverse the word
    	if (splitStringArray[i].length >= 5) {
    		splitStringArray[i].split("").reverse().join("");
    	}
    
    } //end for loop
    
    //join the modified array
    var joinString = splitStringArray.join(" ");
    
    return joinString;
    
    }	//end function
    
    console.log(spinWords("Hey fellow students"));

I am unable to get the words with 5 or more chars reversed. I am trying to first split the string into an array of strings. Then I try to evaluate the length of each string in that array. If the length of the word is 5 or more, then I want to split, reverse, and join that word. Then I want to join the array and display the output.

The output should be "Hey wollef stneduts".



Solution 1:[1]

You have not updated the array with the reverse value. Just assign it back in loop

 function spinWords(string){
    
    //splits string into words separated by a space
    var splitStringArray = string.split(" ");
    
    for (var i = 0; i < splitStringArray.length; i++) {
    //if the word is more than 5 chars, reverse the word
    	if (splitStringArray[i].length >= 5) {
    		     splitStringArray[i]=splitStringArray[i].split("").reverse().join("");
    	}
    
    } //end for loop
    
    //join the modified array
    var joinString = splitStringArray.join(" ");
    
    return joinString;
    
    }	//end function
    
    console.log(spinWords("Hey fellow students"));

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 NullPointer