How to use Split() Reverse() and Join() Methods In Javascript

In this approach, we start by splitting the input string into an array of words using the space delimiter. Then, we iterate through each word in the array. For each word, we check if its length is odd. If it is odd, we reverse the characters of the word using the split, reverse, and join() operations. Finally, we join the array of words back into a string and return the modified string.

Example: The below code example shows the usage of Split, Reverse, and Join to Reverse only the odd-length words

JavaScript
function reverseOWords(str) {
    
    // Split the string into an array of words
    let words = str.split(" ");

    // Iterate through each word
    for (let i = 0; i < words.length; i++) {
        
        // Check if the length of the word is odd
        if (words[i].length % 2 !== 0) {
            words[i] = words[i].split("")
                               .reverse().join("");
        }
    }
    return words.join(" ");
}
const input = "Hellow world how are you?";
console.log("Output:", reverseOWords(input));

Output
Output: Hellow dlrow woh era you?

Time complexity: O(n)

Space complexity: O(n)

Reverse Only the Odd Length Words using JavaScript

Given a string containing words separated by spaces, our task is to reverse only the words with an odd length. The rest of the words remain unchanged.

Example:

Input:
Hellow world how are you?
Output:
Hellow dlrow woh era you?

Below are the approaches to Reverse only the odd-length words:

Table of Content

  • Using Split() Reverse() and Join() Methods
  • Using In-place Reversal and split() method

Similar Reads

Using Split() Reverse() and Join() Methods

In this approach, we start by splitting the input string into an array of words using the space delimiter. Then, we iterate through each word in the array. For each word, we check if its length is odd. If it is odd, we reverse the characters of the word using the split, reverse, and join() operations. Finally, we join the array of words back into a string and return the modified string....

Using In-place Reversal and split() method

In this approach, we convert the input string into an array of characters. We then iterate through each character in the array to find the start and end indices of each word. For each word, we check if its length is odd. If it is odd, we reverse the characters of the word in-place using a helper function. After processing all words, we convert the array of characters back into a string and return the modified string....