Reverse a String with Regex: What Works, What Breaks, and When to Avoid It
A practical review of reversing strings with regular expressions: what the transformation changes, how combining marks and emoji break, and when plain text is the better choice.
Is regex reversal suitable for your use?
Reversing a string with the help of a regular expression suits programming tasks: palindrome checks, test fixtures, puzzles, data-processing steps, and teaching how text is stored. Its main benefit is control over what counts as one unit, such as a byte, a code point, a user-perceived character, or a word. The decisive tradeoff is that reversed text is a new string of characters, not a visual effect. Anyone who copies it, searches for it, or hears it through a screen reader gets the reversed sequence. If people need to read, search, edit, or quote the content, keep the plain text and use a reversed copy only where the reversal itself is the point.
A regex usually does not reverse anything by itself. Most engines match left to right and replace in place, so they cannot reorder a whole string in one substitution. In practice, the regex splits the string into units, and the surrounding code reverses the list and joins it. Some exceptions exist, such as .NET's right-to-left matching mode or looped substitutions in tools like sed. Even then, how well the result holds up depends on how the pattern defines a unit.
What the transformation actually changes
Character reversal rewrites the stored order of characters, so "abc" becomes "cba" in memory, in the clipboard, and in any saved file. That is different from several things also loosely called reversing or mirroring:
- Word reversal reorders words but keeps each word's spelling: "one two three" becomes "three two one".
- Mirror text uses flipped-looking glyphs or substituted Unicode lookalike characters, which change which characters are stored rather than only their order.
- "Fancy font" generators substitute styled Unicode characters (for example, mathematical alphanumeric symbols) and do not reverse anything.
- CSS presentation, such as a transform that flips an element or a forced right-to-left direction, changes how text looks while the stored characters stay the same. Copying such text typically returns the original order, though behavior can vary by browser.
- Bidirectional display is how software lays out right-to-left scripts like Arabic and Hebrew. That text is stored in reading order and displayed right to left. Reversing the stored characters to make it look right to left produces text that reads wrongly.
Why the choice of unit matters
What a reader sees as one character may be several stored units. JavaScript strings use UTF-16 code units, so emoji and many less common characters take two units. A character like "é" may be one code point or a plain "e" followed by a combining acute accent (U+0301). Emoji such as a thumbs-up with a skin-tone modifier, or family emoji joined with zero-width joiners, are sequences of several code points. If reversal splits any of these apart, the output changes meaning or renders as broken symbols.
| Unit of reversal | Typical pattern or method | Input "cafe" + combining accent | Input thumbs-up + skin-tone modifier |
| UTF-16 code unit | JavaScript split('') or a regex without the u flag | Accent moves to the front and attaches to nothing or the wrong letter | Surrogate pairs split; output contains invalid halves |
| Code point | JavaScript /./gsu, Python s[::-1] | Accent moves to the front, detached from the e | Modifier comes first and shows as a standalone swatch before a default-colored thumb |
| Grapheme cluster | \X in Perl, Java, PCRE or Python's third-party regex module; Intl.Segmenter in JavaScript | "éfac" with the accent still on the e | Emoji stays intact |
The examples in the table follow from how each unit is defined. They are not test results from specific devices. How a detached combining mark or orphaned modifier actually renders depends on the font and platform.
Example approaches
Code-point reversal in JavaScript. The u flag makes the dot match whole code points, and the s flag lets it match line breaks. This keeps surrogate pairs together but still separates combining marks and multi-code-point emoji. The fallback handles empty strings, where match returns null.
const reversed = (str.match(/./gsu) ?? []).reverse().join('');
Grapheme-aware reversal in JavaScript. JavaScript regex has no \X, so the built-in segmenter does the splitting instead.
const seg = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
const reversed = Array.from(seg.segment(str), s => s.segment).reverse().join('');
Grapheme-aware reversal in Python. The built-in re module does not support \X, but the third-party regex module does.
import regex
reversed_text = ''.join(reversed(regex.findall(r'\X', text)))
Grapheme-aware reversal in Perl. The string must be decoded text, not raw bytes, or \X will operate on bytes.
my $reversed = join '', reverse $text =~ /\X/g;
Right-to-left matching in .NET. Matches are returned from the end of the string, so concatenating them reverses it. The dot matches single UTF-16 chars, so surrogate pairs and combining sequences are still split.
var reversed = string.Concat(
Regex.Matches(text, ".", RegexOptions.RightToLeft | RegexOptions.Singleline)
.Cast<Match>()
.Select(m => m.Value));
Word reversal that preserves spacing. Splitting on a capturing group keeps the whitespace runs as separate items, so the original spacing survives. Splitting on whitespace without capturing collapses it.
const reversedWords = str.split(/(\s+)/).reverse().join('');
Grapheme segmentation follows Unicode rules that are updated over time. Engines built on different Unicode versions may group some newer emoji sequences differently. Test with the specific characters your input is likely to contain rather than assuming every grapheme-aware method agrees.
Will the result stay readable and usable after copying or sharing?
Because character reversal changes the stored text, the reversed order travels with it. Copy and paste, messaging, and saving all carry the reversed sequence. Correctly segmented output should survive copying as-is. Output that split a grapheme can display differently in each app, since rendering of orphaned combining marks and modifiers is font- and platform-dependent. No destination-specific tests were supplied for this review, so a correct rendering in one app is no guarantee for another.
- Screen readers read stored characters in order, so reversed words are likely to be announced as unfamiliar strings or spelled out. Behavior for specific screen readers was not tested here.
- Search, both on-page find and search engines, matches stored text, so reversed content will not match normal queries for the original words.
- Editing reversed text is awkward: cursor movement, spell-check, and autocorrect all operate on the reversed sequence.
- Right-to-left scripts and mixed-direction text should not be reversed to change their display direction. Use the platform's direction settings or markup so the stored order stays correct.
Provide a plain-text equivalent whenever reversed text appears where people need to understand it, such as next to a puzzle answer, in an alternative-text field, or in a visually hidden label. If the goal is only a visual effect on a web page, CSS presentation keeps the underlying text intact for copying, search, and assistive technology. Verify that in the browsers and tools your audience uses.
Gaps in this review
This review covers documented behavior of the named languages and Unicode text structure. It includes no measured tests of particular apps, fonts, screen readers, or search engines. Treat claims about how reversed or broken sequences render in a given destination as things to check in that destination.