javascriptjoinreversesplit

Reversing words in a string JS without using built in function


Without using the split reverse and join functions, how would one do such a thing?

The Problem Given: Reverse the words in a string Sample Input: "Hello World" Sample Output: "World Hello"

<script>
  var newString = ""; 
  var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)"); 

  newString = theString.split(" ").reverse().join(" ")


  document.write(newString);
</script>

Solution

  • Arrays can be used like stacks out of the box. And stacks are LIFO, which is what you need.

    function reverseWords(str) {
        var word, words, reverse;
    
        words = str.match(/(?:\w+)/g);
        reverse = '';
        while(word = words.pop()) {
          reverse += word + ' ';
        }
    
        return reverse.trim();
    }
    
    reverseWords('hello world');
    

    Or use the call stack as your stack:

    function reverseWords(str) {
      var result = '';
      (function readWord(i = 0) {
        var word = '';
        if(i > str.length) {
            return '';
        }    
        while(str[i] !== ' ' && i < str.length) {
          word += str[i];
          i++;
        }    
        readWord(++i); // Skip over delimiter.
        result += word + ' ';    
      }());
      return result.trim();
    }
    
    reverseWords('hello world');