User Tools

Site Tools

Reversing a string

Two things make reversing a string more complicated than reversing an array, first strings are immutable in Javascript, and second, and more importantly, handling Unicode correctly. Ignoring these issues the algorithms for reversing an array would work on strings.

Since strings are immutable there is no way they can be reversed in-place, they have to be reversed by creating a new string by concatenation.

Unicode is more complex, see and for a more full analysis.

Javascript strings store astral code points as two characters or surrogate pairs. When reversing, the ordering of these surrogate pairs need to be retained. Secondly combining marks like n + ˜ (n\u0303) are also handled by multiple characters in the raw string but are combined into a single glyph. Combining marks also need to retain their ordering. The esrever algorithm below flips the surrogate pairs and combining mark ordering before doing a basic reversion of the string. This ensures these keep their correct ordering in the final string.

λ reversing_a_string

For non-Javascript programming languages the same Unicode traps exist, and they need to be handled carefully.

reversing_a_string.txt · Last modified: 2015/02/03 23:59 by will