Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

olleh

Strings 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:

👍ba

Reversing the order of words

Split the string by spaces instead of characters:

console.log('one two three'.split(' ').reverse().join(' '));

Output:

three two one

Common mistake

Strings have no reverse() method, so calling it directly throws an error:

try {
  'hello'.reverse();
} catch (error) {
  console.log(error.name);
}

Output:

TypeError

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.