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

You want to achieve the following tasks with JavaScript:

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:

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

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

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

The regular expression does the following:

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:

1
    words.reverse();

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