JavaScript Snippet

Reverse a String Safely

Difficulty: Easy

Reversing a string is the textbook one-liner, but the obvious version `[...str].reverse().join('')` corrupts emoji families, flag sequences, and any character with combining marks. This snippet starts with the naive UTF-16 reverse, upgrades to a code-point reverse that fixes surrogate pairs, and ends with `Intl.Segmenter` for true grapheme-cluster correctness. Pick the version that matches the worst-case input you actually expect.

Code Snippets
/

Reverse a String Safely

Reverse a String Safely

Reversing a string is the textbook one-liner, but the obvious version `[...str].reverse().join('')` corrupts emoji families, flag sequences, and any character with combining marks. This snippet starts with the naive UTF-16 reverse, upgrades to a code-point reverse that fixes surrogate pairs, and ends with `Intl.Segmenter` for true grapheme-cluster correctness. Pick the version that matches the worst-case input you actually expect.

JavaScript
Easy
3 snippets
strings
utility
js-web-apis

1,103 views

5

split('') breaks the string into UTF-16 code units, reverse() flips the array in place, and join('') glues the code units back together. For pure ASCII, this is correct, fast, and exactly what every interview question expects. The hidden bug is that any character outside the Basic Multilingual Plane (most emoji, mathematical italics, several historical scripts) is stored as a surrogate pair of two code units, and naive reversal swaps the high and low halves, producing invalid UTF-16. Reach for this only when you can guarantee ASCII input, like reversing a number for a palindrome check.