JavaScript: Reverse the Words in a Sentence without Built-in Function

Introduction

Reversing the words in a sentence means rearranging the words so that the last word appears first, the second last word appears second, and so on. For example, given the sentence "Hello World", the reversed sentence would be "World Hello". This task involves splitting the sentence into individual words and then rearranging them.

To solve this problem without using built-in JavaScript functions like split(), reverse(), or join(), we will have to manually traverse and manipulate the string.

Problem Statement

Create a JavaScript program that:

  • Takes a sentence as input.
  • Reverses the order of words without using built-in methods like split(), reverse(), or join().
  • Outputs the reversed sentence.

Example:

  • Input: "Hello World"
  • Output: "World Hello"

Solution Steps

  1. Identify words in the sentence: Traverse the sentence and extract words.
  2. Store the words in an array: Store each word while traversing.
  3. Reverse the order of words: Rearrange the words to reverse their order.
  4. Display the reversed sentence.

JavaScript Program

Method: Reverse the Words Without Built-in Functions

// JavaScript Program to Reverse the Words in a Sentence without Built-in Functions
// Author: https://www.rameshfadatare.com/

function reverseWords(sentence) {
    let words = [];   // Array to store the words
    let word = "";    // String to temporarily store each word

    // Step 1: Traverse the sentence and extract words manually
    for (let i = 0; i < sentence.length; i++) {
        if (sentence[i] === ' ') {
            // When encountering a space, push the word to the array and reset the word
            if (word.length > 0) {
                words.push(word);
                word = "";  // Reset the word variable for the next word
            }
        } else {
            // Add the character to the current word
            word += sentence[i];
        }
    }

    // Push the last word to the array (if any)
    if (word.length > 0) {
        words.push(word);
    }

    // Step 2: Reverse the order of the words
    let reversedSentence = "";  // String to store the reversed sentence
    for (let i = words.length - 1; i >= 0; i--) {
        reversedSentence += words[i];  // Add each word to the result
        if (i !== 0) {
            reversedSentence += " ";   // Add a space between words
        }
    }

    return reversedSentence;
}

// Example usage
const sentence = "Hello World from JavaScript";
console.log("Original Sentence:", sentence);
console.log("Reversed Words:", reverseWords(sentence));

Output Example

Original Sentence: Hello World from JavaScript
Reversed Words: JavaScript from World Hello

Explanation

Step 1: Extract Words from the Sentence

  • The function traverses the string character by character.
  • It keeps adding characters to a temporary string (word) until it encounters a space.
  • When a space is encountered, the current word is added to the words array, and the word string is reset.
  • The process repeats until the end of the string.
  • If any word remains at the end (without a trailing space), it is added to the array.

Step 2: Reverse the Order of Words

  • After collecting all the words, the function traverses the words array from the last word to the first.
  • Each word is added to a new string (reversedSentence).
  • Spaces are inserted between the words except for the last word.

Handling Edge Cases

  • Multiple spaces between words: This code will ignore multiple spaces between words.
  • Leading and trailing spaces: Leading and trailing spaces are ignored.
  • Empty string: The function will return an empty string if the input is empty.

Conclusion

This JavaScript program demonstrates how to reverse the words in a sentence without using built-in string manipulation functions. The solution involves manually traversing the string, extracting words, and rearranging them in reverse order. This approach is useful for understanding low-level string manipulation and handling sentence structure.

Comments