Reversing a string means changing its order so that the last character becomes the first, and the second last character becomes the second, and so on. This straightforward, example-based article shows you a couple of different ways to reverse a given string in JavaScript.
Using the split(), reverse(), and join() methods
Example:
const reverseString = (str) => {
return str.split('').reverse().join('');
};
console.log(reverseString('ABCDEF'));
console.log(reverseString('123456'));
Output:
FEDCBA
654321
Using a loop
Example:
const reverseString = (str) => {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
};
console.log(reverseString('Welcome to Sling Academy!'));
Output:
!ymedacA gnilS ot emocleW
Using the spread operator
This approach is quite similar to the first approach, but instead of using the split() method, we use the spread operator.
Example:
const str = "This is a secret message!";
const reversed = [...str].reverse().join("");
console.log(reversed);
Output:
!egassem terces a si sihT