Reverse Text in JavaScript

Learn multiple ways to reverse strings in JavaScript, from the classic split-reverse-join to spread operators and reduce. Handle Unicode correctly with modern techniques.

Programming

Detailed Explanation

Reversing Strings in JavaScript

JavaScript offers several approaches to string reversal, each with different tradeoffs for readability, performance, and Unicode correctness.

Method 1: Split-Reverse-Join (Classic)

const reversed = str.split("").reverse().join("");

Warning: This breaks with emoji and surrogate pairs because split("") splits on UTF-16 code units, not Unicode code points.

"Hello 👋".split("").reverse().join("");
// "�👋 olleH" — broken!

Method 2: Spread Operator (Unicode-Safe)

const reversed = [...str].reverse().join("");

The spread operator iterates over Unicode code points, correctly handling emoji and multi-byte characters:

[..."Hello 👋"].reverse().join("");
// "👋 olleH" — correct!

Method 3: Array.from (Unicode-Safe)

const reversed = Array.from(str).reverse().join("");

Equivalent to the spread operator approach.

Method 4: For Loop

function reverse(str) {
  let result = "";
  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i];
  }
  return result;
}

Note: This also has the UTF-16 surrogate pair issue. Use for...of for Unicode safety:

function reverse(str) {
  let result = "";
  for (const char of str) {
    result = char + result;
  }
  return result;
}

Method 5: Reduce

const reversed = [...str].reduce((acc, char) => char + acc, "");

Performance Comparison

For typical strings (< 10,000 characters), all methods perform similarly. For very large strings, the for-loop approach with pre-allocated array is fastest. The spread + reverse + join method offers the best balance of correctness and readability.

Use Case

JavaScript string reversal appears in frontend coding challenges, technical interviews for web developer positions, and practical tasks like building text transformation tools, form validators, and educational coding platforms.

Try It — Reverse Text

Open full tool