Languages
[Edit]
EN

JavaScript - reverse words in a given string

0 points
Created by:
Rogan-Wilkes
727

In this article, we would like to show you how to reverse words in a given string in JavaScript.

Practical example

In the example below, we split the string into elements, reverse their order, and then we join them all together.

// ONLINE-RUNNER:browser;

function reverseString(string) {
    return string.split(' ').reverse().join(' ');
}

console.log( reverseString('Hello world'));             // world Hello
console.log( reverseString('Reverse words in string')); // string in words Reverse

Output:

world Hello
string in words Reverse

Reference

  1. Array.prototype.reverse() - MDN Docs

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - reverse words in a given string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join