DEV Community

Ian Felix
Ian Felix

Posted on

3 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay