Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Javascript Program To Reverse Words In A Given String

  • Last Updated : 15 Dec, 2021

Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”

reverse-words

Examples

Input: s = “geeks quiz practice code” 
Output: s = “code practice quiz geeks”

Input: s = “getting good at coding needs a lot of practice” 
Output: s = “practice of lot a needs coding at good getting”

Algorithm:  

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Below is the implementation of the above approach: 

Javascript




<script>
// Javascript program to reverse 
// a String
      
// Reverse the letters of 
// the word 
function reverse(str, start, end)
{
    // Temporary variable to 
    // store character 
    let temp;        
          
    while (start <= end) 
    {
        // Swapping the first and 
        // last character 
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}
      
// Function to reverse words
function reverseWords(s)
{
    // Reversing individual words as
    // explained in the first step
    s = s.split("");
    let start = 0;
    for (let end = 0; 
             end < s.length; end++) 
    {
        // If we see a space, we reverse 
        // the previous word (word between 
        // the indexes start and end-1 
        // i.e., s[start..end-1]
        if (s[end] == ' '
        {
            reverse(s, start, end);
            start = end + 1;
        }
    }
    // Reverse the last word
    reverse(s, start, s.length - 1);
          
    // Reverse the entire String
    reverse(s, 0, s.length - 1);
    return s.join("");
}
      
// Driver Code
var s = 
"i like this program very much ";
      
document.write(reverseWords(s));
// This code is contributed by avanitrachhadiya2155
</script>

Output:

much very program this like i

Another Approach:

we can do the above task by splitting and saving the string in a reverse manner. 

Below is the implementation of the above approach:

Javascript




<script>
// JavaScript program to reverse a string
var s = ["i", "like", "this"
         "program", "very", "much"];
                                          
var ans ="";
for (var i = 5; i >= 0; i--)
{
    ans += s[i] + " ";
}
document.write(
"Reversed String:"+ "<br>");
document.write(
ans.slice(0,ans.length-1));
</script>

Output:

Reversed String:
much very program this like i

Time Complexity: O(n) 

Without using any extra space:
The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.   

Below is the implementation of the above approach:

Javascript




<script>
// Javascript code to reverse a string
  
// Reverse the string
function RevString(s, l)
{    
    // Check if number of words 
    // is even
    if (l % 2 == 0)
    {
        // Find the middle word
        let j = parseInt(l / 2, 10);
  
        // Starting from the middle start
        // swapping words at jth position 
        // and l-1-j position
        while (j <= l - 1)
        {
            let temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
  
    // Check if number of words is odd
    else
    {
        // Find the middle word
        let j = parseInt((l / 2), 10) + 1;
  
        // Starting from the middle start
        // swapping the words at jth
        // position and l-1-j position
        while (j <= l - 1)
        {
            let temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
  
    let S = s[0];
  
    // Return the reversed sentence
    for(let i = 1; i < 9; i++)
    {
        S = S + " " + s[i];
    }
    return S;
}
  
// Driver code
let s = "getting good at coding "
        "needs a lot of practice";
              
let words = ["getting", "good", "at",
             "coding", "needs", "a",
             "lot", "of", "practice"];
document.write(RevString(words, 9));
  
// This code is contributed by suresh07
</script>

Output:

practice of lot a needs coding at good getting

Please refer complete article on Reverse words in a given string for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!