Reverse the word in a string with the same order in javascript I want reverse the string with the same order. We should not use the Array functions like split(), .reverse() and some other array functions also except array.length.

Here i am attached my code. How to achieve that thing more efficiently.

var str = "i am javascript";
// result "i ma tpircsavaj"
function reverseString(myStr){
    var strlen = myStr.length, result = "", reverseStr = "", reverseStrArr = [];
  for(var i = strlen-1; i &gt;= 0; i--){
    reverseStr +=  myStr[i];
  }

    for(var j = 0; j &lt; strlen; j++){
    if(reverseStr[j] == " "){
      reverseStrArr.push(result);
      result = "";
    }else{
      result += reverseStr[j];
      if(j + 1 == strlen){
        reverseStrArr.push(result);
        result = "";
      }
    }
  }

  for(var k=reverseStrArr.length - 1; k &gt;= 0; k--){
    result += reverseStrArr[k] + " "
  }
  console.log(result);
}
reverseString(str);
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 &gt;= 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 &lt; 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 &gt;= 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.