Split the words out of a string and reverse their order with JavaScript

You want to achieve the following tasks with JavaScript:

  • Extract the words out of a string

  • Reverse the order of the extracted words.

Let’s see how you can split a string based on its words. There are two simple options.

Either you use the split() function and pass to it as argument a space character. The function returns the extracted words into an array:

    var testString = "this is a simple test string!";
    var words = testString.split(" ");

or you are using a simple regular expression for splitting the words:

    var testString = "this is a simple test string!";
    var words = testString.match(/[^\s]+/g);

The regular expression does the following:

  • The […] defines a set of characters (character class) that can be matched.

  • The ^ symbol inside the character class defines that the following set of characters should not be matched.

  • The characters that should be skipped are defined with \s which match all the whitespace (space, tab, etc.) characters. This practically means, that every other character will match.

  • The + symbol will match sets of characters (words) that are at least one character long.

  • The g letter gives us a global matching in the complete string, so that all words are found.

Now the words variable is an array which contains the splitted words. In order to reverse the order of the array elements, just use the reverse() function provided from the Array object:


The reverse function changes the values of the original words array, since the function applies to the reference of the array. For this reason, you do not have to store the resulted value in a new array. For more information about which array function are changing the original array and which not, you can read this article..

comments powered by Disqus