DEV Community

Ian Felix
Ian Felix

Posted on

How to invert a string

First, we need to transform the string into a list of characters. We can use the split() method to do that.

const str = 'Hello World';
const chars = str.split('');
console.log(chars); // ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Enter fullscreen mode Exit fullscreen mode

Then, we need to reverse the list of characters. We can use the reverse() method to do that.

const chars = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
const reversedChars = chars.reverse();
console.log(reversedChars); // ['d', 'r', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'o', 'e', 'l', 'l', 'H']
Enter fullscreen mode Exit fullscreen mode

Finally, we need to join the list of characters back into a string. We can use the join() method to do that.

const reversedChars = ['d', 'r', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'o', 'e', 'l', 'l', 'H'];
const reversedStr = reversedChars.join('');
console.log(reversedStr); // 'dlrow olleH'
Enter fullscreen mode Exit fullscreen mode

So, we have a string that is the reverse of the original string.

const str = 'Hello World';
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 'dlrow olleH'
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️
[...str].reverse().join('')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frankwisniewski profile image
Frank Wisniewski

seen 1000 times and wrong 1000 times...

const str = 'Hello 😊 World';
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 'dlroW �� olleH'
Enter fullscreen mode Exit fullscreen mode