We can easily reverse words in a string in JavaScript using the JavaScript split(), reverse() and join() methods. Below is a function we will create to reverse words in a string.
function reverseWords(str){
var newString = str.split(" ");
newString.reverse();
newString = newString.join(" ");
return newString;
};
Here is the function in use with an example string:
function reverseWords(str){
var newString = str.split(" ");
newString.reverse();
newString = newString.join(" ");
return newString;
};
var someString = "This is an example string with words";
console.log(reverseWords(someString));
#Output:
words with string example an is This
When using string variables in JavaScript, we can easily perform string manipulation to change the values or order of the words in our string.
One such manipulation is to reverse the words in a string.
To reverse the words in a string, we can first use the split() method to get an array of each word in the string, and then use the reverse() method to return the array with all of the items in reverse.
After reversing the array we then join the words together using the JavaScript join() method.
Below is our function once again on how to reverse the words in a string using JavaScript.
function reverseWords(str){
var newString = str.split(" ");
newString.reverse();
newString = newString.join(" ");
return newString;
};
Reversing Each Word in a String Using JavaScript
If you are looking to reverse each word in a string, we can modify our examples from above slightly. Instead of reversing the order of the words, we will reverse the letters of each word.
In this case, we will split() the string to get each word, and then loop over each word and reverse it with string slicing.
We have a post on reversing a string, it basically uses the same idea as our function above.
Below is an example of how to reverse each word in a string with JavaScript.
function reverseEachWord(str){
var newStringArr = str.split(" ");
for ( var i=0; i
And here is the function in use with an example string:
function reverseEachWord(str){
var newStringArr = str.split(" ");
for ( var i=0; i
Hopefully this article has been helpful for you to learn how to reverse words in a string using JavaScript.