EN
JavaScript - reverse words in a given string
0 points
In this article, we would like to show you how to reverse words in a given string in JavaScript.
In the example below, we split the string into elements, reverse their order, and then we join them all together.
xxxxxxxxxx
1
function reverseString(string) {
2
return string.split(' ').reverse().join(' ');
3
}
4
5
console.log( reverseString('Hello world')); // world Hello
6
console.log( reverseString('Reverse words in string')); // string in words Reverse
Output:
xxxxxxxxxx
1
world Hello
2
string in words Reverse