Search code examples
javascriptstringreverse

Revers a string word by word without using inbuilt function in javascript


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

console.log(reverse1("I like this program very much"));

output: // hcum yrev margorp siht ekil I

but expected output: I ekil siht margorp yrev hcum

please can any one answer this....???


Solution

  • You are reversing the whole string. If you want to use a single function and assuming the string contains spaces only, you can loop through every character of the string.

    If you encounter a space, you can append that to the result. If you encounter another character, you can prepend that to a temporary string to build a reversed version of the word.

    Then append the reversed version of word to the result when the next character is either a space or when it is the last character in the iteration.

    function reverse1(str) {
      let result = "", tmp = "";
      for (let i = 0; i < str.length; i++) {
        if (str[i] === ' ') {
          result += ' '; continue;
        }
        tmp = str[i] + tmp;
        if (str[i + 1] === undefined || str[i + 1] === ' ') {
          result += tmp; tmp = "";
        }
      }
      return result;
    }
    
    console.log(reverse1("I like this program very much"));
    console.log(reverse1("    I like this program very much   "));
    console.log(reverse1("abc"));