Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Reverse Words In A String Using JavaScript

TwitterFacebookRedditLinkedInHacker News

Back on the topic of possible programming interview questions, you may at some time in your career be asked to reverse words in a string. This is a much simpler problem and may be more likely to appear on a technical phone screening.

In it’s simplest form, you would assume all space separated string collections to be words. To clarify, it doesn’t matter if you’re looking at a true word or just some jumbled text separated by a space character.

This problem can be solved in just a few lines of JavaScript, but our logic will be as follows:

  1. Split the desired string by space character delimiters
  2. Determine how many words have been separated
  3. Loop backwards through the split string, while creating a new string
  4. Return the new string

Lucky for us, in Java and JavaScript we don’t have to worry about coming up with our own string splitting algorithm. In both these languages you can do String.split(delimiter) to split the string into an array.

function StringUtil() {

    this.reverseWords = function(str) {
        var result = "";
        var wordArray = str.split(" ");
        for(var i = wordArray.length - 1; i >= 0; i--) {
            result += wordArray[i] + " ";
        }
        return result.trim();
    }

}

If you really wanted to go the extra mile and do the grunt work, you could create a split string function that would look like this:

String.prototype.splitStr = function(delimiter) {
    var stringArray = [];
    var tempStr = "";
    for(var i = 0; i < this.length; i++) {
        if(this.charAt(i) === delimiter) {
            stringArray.push(tempStr);
            tempStr = "";
        } else {
            tempStr += this.charAt(i);
        }
    }
    if(tempStr !== "") {
        stringArray.push(tempStr);
    }
    return stringArray;
}

The above code will be slightly different for Java because you’d be using a StringBuilder instead, but for the most part it is the same.

Conclusion

This is a small and simple algorithm that is very likely to be asked on a technical phone screening rather than a technical interview. You could take the short route in solving this problem, or take the impressive extra mile approach by designing the split string algorithm.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.