Text Effects

How to Reverse a String in JavaScript, Python and PHP

Code examples for reversing strings in popular languages, why naive methods break emoji and accented letters, and how to do it correctly.

Reversing a string is a common programming exercise, and a surprisingly good test of how well you understand text encoding.

JavaScript

The simple version:

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

This breaks emoji and some symbols, because split('') splits by UTF-16 code units, and many emoji use two. A better version uses the string iterator:

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

For full correctness with combined characters (such as flags, skin-tone emoji or letters with separate accent marks), use Intl.Segmenter:

const seg = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
const reversed = [...seg.segment(str)].map(s => s.segment).reverse().join('');

Python

reversed_text = text[::-1]

Python slices by Unicode code points, which handles most text but can still separate combining marks and multi-part emoji. Libraries such as grapheme or the regex module's \X pattern can split by grapheme clusters.

PHP

strrev() works only on single-byte strings and corrupts multi-byte UTF-8 text such as "café". A safer approach:

$reversed = implode('', array_reverse(mb_str_split($text)));

mb_str_split() is available from PHP 7.4.

Reversing words instead of characters

// JavaScript
const reversedWords = str.split(/\s+/).reverse().join(' ');

Try it without code

The NS Tools Hub reverse text generator uses grapheme-aware reversing, so you can compare your function's output with a correct result for tricky test strings.

Frequently asked questions

How to reverse a string in Python?

To reverse a string in Python, use slicing: text[::-1]. For text with combining accents or complex emoji, split it into grapheme clusters first with a library.

How to reverse a string in PHP?

To reverse a string in PHP safely, use implode('', array_reverse(mb_str_split($text))). The built-in string reverse function strrev breaks multi-byte UTF-8 characters.

How to reverse a string in Java?

For a reverse string in Java, use new StringBuilder(text).reverse().toString(). StringBuilder keeps surrogate pairs together, but complex emoji sequences may still need grapheme-aware handling.

How to reverse a string without breaking emoji?

To reverse string without breaking emoji in JavaScript, split by graphemes with Intl.Segmenter, reverse the array and join it. Spreading the string with [...str] handles most emoji but not every combined sequence.

How to reverse word order in JavaScript?

Reverse word order in JavaScript with str.split(/\s+/).reverse().join(' '). To reverse words in a sentence while keeping punctuation attached, split on spaces only.

Try the free Reverse Text Generator

Reverse letters or words, flip text upside down and create mirror text with one click.

Open Reverse Text Generator