Reversing a String With JavaScript
Just for a little fun, I was thinking of a couple of ways to reverse a string. This seems like a pretty mundane task, but it could very easily crop up in an interview question.
The first implementation one could think of would be relatively easy:
1 | function reverseStr(s) { |
The second implementation I thought of was using charat and length, which can be considered quite a crude method.
1 | var string = "Having fun with reversing strings!!"; |
Perhaps a third implementation that’s pretty fast is using a simple for loop
1 | function reverseStr(s) { |
So I did a little more research and went over to a post on Stack Overflow where there were quite a few implementations with solid examples. Turns out that the first implementation should not be used:
1 | // never use this or a similar method!! |
The simple reason being is explained quite well:
Why? Because it contains an astral symbol (𝌆) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ in the last mañana actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).
To properly reverse a string there is a library written by Mathias, is written as a JavaScript library and is capable of Unicode-aware string reversal. It also has a utility/binary so you can reverse strings in your terminal as well :)