Open In App

Reverse all the Words of Sentence JavaScript

Last Updated : 10 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sentence, Our task is to reverse all the words in the sentence while maintaining their order.

Example: 

Input:  "Hello World"
Output: "olleH dlroW"

Below are the approaches to reverse all the words of sentence JavaScript:

Using Built-in Functions

In this approach, The function reverseWords takes a sentence as input, splits it into an array of words, iterates through each word to reverse it, and then joins the reversed words back into a sentence. Finally, it returns the reversed sentence.

Example: The example below shows the program to reverse all the words of a sentence using Built-in Functions.

JavaScript
function reverseWords(sentence) {
  let words = sentence.split(" ");
  for (let i = 0; i < words.length; i++) {
    words[i] = words[i].split("").reverse().join("");
  }
  let reversed = words.join(" ");
  return reversed;
}

let input = "Hello World";
let output = reverseWords(input);
console.log(output);

Output
olleH dlroW

Time Complexity: O(n * m), where n is the number of words in the sentence and m is the average length of each word.

Auxiliary Space: O(n).

Using Iterative Reversal

In this approach, we iterate through each character of the input sentence and if we encounter a space, we add the current word (substring from the last space encountered to the current position) reversed to the result string. Then, we reverse the last word append it to the result, and print the reversed sentence.

Example: Implementation of a program to reverse all the words of a sentence using Iterative Reversal

JavaScript
function reverse(sentence) {
    let reversed = ""; 
    let start = 0;

    for (let i = 0; i < sentence.length; i++) {
        if (sentence[i] === " ") {
            reversed += revStr(sentence.substring(start, i)) + " ";
            start = i + 1;
        }
    }

    reversed += revStr(sentence.substring(start));
    return reversed;
}

function revStr(str) {
    let rev = "";
    for (let i = str.length - 1; i >= 0; i--) {
        rev += str[i];
    }
    return rev;
}

let input = "Hello World";
let output = reverse(input);
console.log(output);

Output
olleH dlroW

Time Complexity: O(n), where n is the length of the input sentence.

Auxiliary Space: O(n).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads