How to reverse a string
Short answer
Strings have no reverse method, but arrays do. Split the string into characters, reverse the array and join it back:
console.log('hello'.split('').reverse().join(''));Output:
ollehStrings with emoji
split('') cuts an emoji into two halves and breaks it. The ... operator splits a string into whole characters:
console.log([...'ab👍'].reverse().join(''));Output:
👍baReversing the order of words
Split the string by spaces instead of characters:
console.log('one two three'.split(' ').reverse().join(' '));Output:
three two oneCommon mistake
Strings have no reverse() method, so calling it directly throws an error:
try {
'hello'.reverse();
} catch (error) {
console.log(error.name);
}Output:
TypeErrorFunctions used in this recipe
- String.prototype.split — Splits a string into an array by a separator.
- Array.prototype.reverse — Reverses an array in place.
- Array.prototype.join — Joins array elements into a string.