This function should work for you:

function myFunction(string) {
    return string.split("").reverse().join("").split(" ").reverse().join(" ")
};
Answer from Kunal Jain on Stack Overflow
🌐
Inspector
inspector.dev › home › how to reverse a string in javascript – fast tips
How to reverse a string in Javascript - Fast tips
November 7, 2024 - Three basic ways to reverse a string in JavaScript: utilizing the built-in reverse() method, a for loop, and the spread operator + reverse().
🌐
freeCodeCamp
freecodecamp.org › news › how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb
Three Ways to Reverse a String in JavaScript
March 14, 2016 - Interviewers may ask you to write different ways to reverse a string, or they may ask you to reverse a string without using in-built methods, or they may even ask you to reverse a string using recursion. There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.
🌐
SamanthaMing
samanthaming.com › pictorials › how-to-reverse-a-string
How to Reverse a String in JavaScript | SamanthaMing.com
Write a function that reverse a string. ... In JavaScript, there is no built-in method to reverse a string. There is however, a built-in method to reverse an array.
🌐
TutorialsPoint
tutorialspoint.com › reversing-words-in-a-string-in-javascript
Reverse Words in a String in JavaScript
const str = 'this is a sample string'; const reverseWords = str => { let reversed = ''; reversed = str.split(" ") .map(word => { return word .split("") .reverse() .join(""); }) .join(" "); return reversed; }; console.log(reverseWords(str));
🌐
CodeSignal
codesignal.com › learn › courses › practicing-string-operations-and-type-conversions-in-javascript › lessons › reversing-words-in-a-string-in-javascript
Reversing Words in a String in JavaScript
Afterward, it forms a single string with these reversed words, producing "olleH taen 321_srevol_tpircsavaj". Therefore, if you call reverseWords("Hello neat javascript_lovers_123"), the function should return "olleH taen 321_srevol_tpircsavaj".
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-string-exercise-60.php
JavaScript - Reverse words in a given string
If the input is a non-empty string, the function splits the text into an array of words using a regular expression that matches non-whitespace characters. It then iterates through each word in the array of words. For each word, it splits it into an array of characters. It reverses the array, joins the characters back into a string, and adds it to the 'reverse_word' string with a space.
🌐
Medium
medium.com › codex › reverse-string-on-javascript-d6a4e0ce8c68
Reverse String on JavaScript. Did you ever try to read an open book… | by Norberto Santiago | CodeX | Medium
December 24, 2021 - As you can see in the for loop, the i starting point represents the last character of the string. As long as i is longer or equals 0, i will decrement. For each iteration, the last character will be added to newString, forming the result reversed string we want. ... We get a pool. ... Now that we tried reversing with the good old for loop, let’s go ahead and do some JavaScript tricks. First, let’s reverse a single-word ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-reverse-words-in-a-given-string
Javascript Program To Reverse Words In A Given String - GeeksforGeeks
// 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 = Math.floor(l / 2); // Starting from the middle, swap words while ...
Published   July 23, 2025
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Write a function to reverse words in a string - JavaScript - The freeCodeCamp Forum
November 19, 2018 - I got below test as a part of my job interview and I know how to reverse a string but don’t know how to reverse every third word in a string. Test is Using ES5 or ES6, write a function ‘reverseStringWords’ that will reverse every **third** word in a string.
🌐
Go Make Things
gomakethings.com › how-to-reverse-each-word-in-a-string-with-vanilla-javascript
How to reverse each word in a string with vanilla JavaScript | Go Make Things
Inside the callback function, I would again use the String.prototype.split() method to create an array of letters for the word. I would use the Array.prototype.reverse() method to reverse the letters, then the Array.prototype.join() method to ...
🌐
Programiz
programiz.com › javascript › examples › reverse-string
JavaScript Program to Reverse a String
To understand this example, you should have the knowledge of the following JavaScript programming topics: ... // program to reverse a string function reverseString(str) { // empty string let newString = ""; for (let i = str.length - 1; i >= 0; i--) { newString += str[i]; } return newString; ...
Top answer
1 of 4
7

I would split this into two function, simply because they do different things:

First a simple string reverser:

function reverseString(input)
{
    var output = "";
    for(var i = input.length - 1; i >= 0; i--) {
        output +=  input[i];
    }
    return output;
}  

This is an easy function that everybody can understand. But we need to reverse words, so we make another function for that.

function reverseWords(input)
{
    var word = "", output = "";
    for(var i = 0; i < input.length; i++) {
        if (input[i] == " ") {
            output += reverseString(word) + " ";
            word = "";
        }
        else {
            word += input[i];
        }
    }
    return output + reverseString(word);
}

And that's it. Now this might not be the niftiest, or shortest, solution, but it is one that reasonably easy to understand, and you get two functions for the price of one.

I had to correct this code after a comment from Blindman67 saying it didn't work for some cases.

A shorter version is also possible:

function reverseWordsShorter(input)
{
    var word = "", output = "";
    for(var i = input.length - 1; i >= 0; i--) {
        if (input[i] == " ") {
            output = " " + word + output;
            word = "";
        }
        else {
            word += input[i];
        }
    }
    return word + output;
}

Also notice that there's no erroneous space at the end anymore.

2 of 4
7

Your function has two bugs

  1. Adds an extra space to the end of the string. Eg for "the cat sat on the mat" you return "eht tac tas no eht tam ". The input string is 22 characters long and the returned string is 23 characters long.

  2. Related to the first. If the input string starts with a space the returned string removes it. Eg for " the cat sat on the mat" you return "eht tac tas no eht tam ".


Code style

This section will cover source code style. These points are independent of the algorithms logic.

  • You are missing the semicolon for the line inside the last for statement.

  • Use === or !== rather than == or !=

  • You should never see for (var i If you use a var it should be declared at the top of the function or use for (let i. You can also use const in for...of and for...in loops. Eg for (const i of foo) {

  • Don't scrunch up the code. Space between ) {, for (, if (, } else and else {. Also operators should be separated by space. i = strlen-1 should be i = strlen - 1

  • Use const for variables that do not change.

    • The variable strlen does not change, thus it should be a constant.
    • The variable reverseStrArr holds a reference to an array. That reference never changes so the variable should be declared as a constant. const reverseStrArr = [];
  • You should try to avoid adding a variable's type to its name.

    Names need only fit the context (have semantic meaning) of the scope/function they are declared in.

    • myStr better as words or sentence
    • strLen better as just length or charCount or even just len
    • reverseStr better as reversed
    • reverseStrArr maybe reversedWords

Loop variables

You don't need to declare a different variable of each loop. You need only do that if the loops are nested.

// Nested 
var i,j;
for (i = 0; i < 10; i++) {
    for (j = 0; j < 10; j++) { /*...*/ }
}
//or 
for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) { /*...*/ }
}

// Sequential
var i;
for (i = 0; i < 10; i++) { /*...*/ }
for (i = 0; i < 10; i++) { /*...*/ }

//or 
for (let i = 0; i < 10; i++) { /*...*/ }
for (let i = 0; i < 10; i++) { /*...*/ }

Algorithms Logic

This section looks at how your function solves the problem and possible ways to improve it.

Array as a stack

You are using the array reverseStrArr as a stack. An array becomes a stack only by the way you use it, it is an abstracted stack.

Stacks are first in last out. You add items one at a time to the top of the stack, then you remove items one at a time from the top.

The two array function push() and pop() provide a fast way to use JS arrays as a stack.

As a stack the final loop where you create the result string can be simplified as

while (reversedWords.length) {
    result += " " + reversedWords.pop();
}

(I think the rules will let us use pop.)

Unneeded steps

  1. The Last Word

In the second loop you have the statement if(j + 1 == strlen) { to push the last result to the array, then you clear result.

If you remove that statement and its content you can have result hold the last word. In the following loop result already has the first word so you can add the space then word rather than word an space (trailing space bug)

This fixes both bugs.

  1. Repeated Logic

The first loop goes from last to first creating a reversed string, then the next loop indexes the string created from first to last. Its like writing backward so the when you read forward its backward... LOL

The first loop is not needed. Just read the sentence string backward as you process it.


Rewrite

Putting all the above into your function we get a much simpler source and fix the bugs at the same time.

function reverseString(words) {
    const reversed = [], len = words.length;
    var result = "", i = len;
    while (i-- > 0) {
        if (words[i] == " ") {
            reversed.push(result);
            result = "";
        } else { 
            result += words[i];
        }
    }
    while (reversed.length) { 
        result += " " + reversed.pop();
    }
    return result;
}

Alternative

The rewrite is still a little too complex .

I used two loops to first create a stack of words and then use the stack to rebuild the sentence.

You can do both within the one loop removing the need to use a stack.

function reverseWords(sentence) {
    var word = "", reversed = "", i = sentence.length;
    while (i-- > 0) {
        if (sentence[i] === " ") {
            reversed = " " + word + reversed;
            word = "";
        } else { word += sentence[i] }
    }
    return word + reversed;
}

Surrogates, Codepoints, Emoji, modifiers, sequences

I see that in the accepted answer there are comments regarding Emoji (surrogate Unicode characters)

In JavaScript strings are iteratable. The iterator handles all codepoint characters as single items.

Note: Single emoji can be created from one or more codepoints. eg is one emoji (on Chrome win10) but contains 6 codepoints or 8 Javascript string Unicode characters. See note at bottom of answer.

Using iterators to step over strings and you need not worry about character sequences.

Unfortunately iterators don't run backward. As we can not use many of the Array functions we are limited in how to solve the problem

Simplest solution.

To solve the problem of surrogate characters (within the restriction of the question) we can use a very quick hack that converts the input string to an array.

sentence = [...sentence]; // separates codepoints

The rest of the function remains unchanged because we used bracket notation to index the strings.

Example

Shows pass and failure modes when reversing surrogates via string iterator.

    function reverseWords(sentence) {
        sentence = [...sentence];
        var word = "", reversed = "", i = sentence.length;
        while (i-- > 0) {
            if (sentence[i] === " ") {
                reversed = " " + word + reversed;
                word = "";
            } else { word += sentence[i] }
        }
        return word + reversed;
    }
    
    
    const test1 = " The cat  on the mat ";
    const test2 = `  \u200D\u200D \u{1F3C4}\u200D\u2642\uFE0F`;

    log(test1);
    log("Reverse...");
    log(reverseWords(test1));
    
    log("--------------------------------------");
    log("Emoji modifiers and sequences may fail.");

    log(`${test2} Reversed is...`);
    log(`${reverseWords(test2)}`);

    
    
    function log(textContent) { 
        info.appendChild(Object.assign(document.createElement("div"),{textContent}));
    }
#info {
font-size: large;
}
<code id="info"><code>

Note: Emoji modifiers and sequences rely not only on how Javascript handles the string but also how the device OS interprets the string.

Use String.prototype.codePointAt() to locate modifiers, sequences, gruping, etc

For a full Emoji rundown Unicode Emoji Technical Standard

🌐
Educative
educative.io › answers › reversing-a-string-using-javascript
Reversing a string using JavaScript
All we have to do is iterate the string in reverse and append each character to a new empty string. Let’s have a look at the code: ... Each character above is picked from the end of the given string; o from "hello" is picked first and appended ...
🌐
DEV Community
dev.to › andrewjwilliams › algorithm-practice-reverse-words-in-a-string-1n2g
Algorithm Practice: Reverse Words in a String - DEV Community
February 8, 2021 - Despite these added spaces, the returned string should only have single spaces separating words with no leading or trailing spaces (basically we return normal sentences, just reversed). After I first read the prompt, I knew I was going to need a way to store each word from the inputted string. I also knew I could use some trusty JavaScript methods to help meet the sentence requirements put in place by the prompt.
🌐
AlgoCademy
algocademy.com › link
Reverse Words in JavaScript | AlgoCademy
The naive solution involves manually iterating through the string to identify words and then constructing the reversed string. This approach is not optimal due to its complexity and potential for errors. The optimized solution leverages built-in JavaScript methods to achieve the desired result ...
🌐
Medium
medium.com › @DylanAttal › reverse-a-string-in-javascript-3486bea83b6f
Reverse a string in JavaScript. This article is a part of the series… | by Dylan Attal | Medium
April 30, 2019 - Reverse a string in JavaScript Reversing a string seems simple enough, right? Just put the letters in the opposite order! But when thinking algorithmically, we have to be exact. We have to break down …
🌐
Quora
quora.com › How-do-you-reverse-the-order-of-words-in-a-string-in-JavaScript
How to reverse the order of words in a string in JavaScript - Quora
Answer (1 of 2): var string = "Text 1 - Text 2 - Text 3 - Text 4"; // "Text 1 - Text 2 - Text 3 - Text 4" var array = string.split(' - ') // ["Text 1", "Text 2", "Text 3", "Text 4"] array.reverse() // ["Text 4", "Text 3", "Text 2", "Text 1"] array.join(' - ') /
🌐
RunJS
runjs.app › blog › reverse-a-string-in-javascript
Reverse a String in JavaScript: 3 Expert Methods You Should Know
June 15, 2023 - Let me break down what each method does so you can understand how these built-in JavaScript methods can help us in string reversal. You can use split() to turn a string into an array of words or characters.
🌐
GitHub
gist.github.com › willread › 3444673
Reverse the words in a string · GitHub
Reverse the words in a string · Raw · reverseWords.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.