How to reverse a string in JavaScript
TL;DR
Watch this 2 minute clip. Scroll down to see each step with code samples.
Step 1: Create a string
Create a string using double quotes, single quotes or back quotes.
let s = '😮🐻🐯🦁';
Step 2: Convert the string to an array of characters
Use the spread operator (...) inside square brackets to create an array of characters.
let s = '😮🐻🐯🦁';
[...s]
// ['😮', '🐻', '🐯', '🦁']
Step 3: Reverse the array
Use the .reverse() method to reverse the array.
let s = '😮🐻🐯🦁';
[...s].reverse();
// ['🦁', '🐯', '🐻', '😮']
Step 4: Convert the array back into a string
Use the .join() method with empty quotes to recombine the array into a string
let s = '😮🐻🐯🦁';
[...s].reverse().join('');
// '🦁🐯🐻😮'
Step 5: Assign the result to a variable
Reversing a string is not permanent. Assign the result to a variable if you want the change to persist.
let s = '😮🐻🐯🦁';
s = [...s].reverse().join('');
console.log(s);
// '🦁🐯🐻😮'