Why touch so simple theme with javascript ? Reverse a string ? Is that so really simple as we think ? Does give this feature problems ? Just google how to reverse a string with javascript .
string.split('').reverse().join('')
The most simple way to do it without compromise the performance of your code, however this awesome line has a couple of bad things that you should consider if your project needs handle
The following examples will show cases where this line code fails :
Why this happens ? Simple, the codification. The string will be wrong reversed for UTF-16 strings that contain surrogate pairs, for example characters outside of the basic multilingual plane. If you want a really detailed explication (and want to sleep a little) read this article, it will clear up your doubts.
Solution
If you're one of the unlucky ones who suffer with this problem and must solve it, maybe you're not so unlucky.
The esrever library, created and published by mathiasbynens will solve this problem without any kind of pain.
How to use it
The library has a detailed documentation of how to include it and use it in every javascript environment (server side, browser, shell). The following example shows how to use it in the browser :
This function takes a string and returns the reversed version of that string, correctly accounting for Unicode combining marks and astral symbols.
Do i really need to use a library to reverse a string ?
How i said before, you can use the most known function to reverse a string if you don't use UTF-16 strings.
Are you victim of this issue ? Tell us in the comment box how this solution works for you.
0 Comments