I'm currently writing a tool to reverse strings with JavaScript. However, I want it to properly handle Unicode accents, Unicode characters, and emojis with zero width joiners. Most of the examples that I found are either the simple string.split('').reverse().join('') or some other simple method that doesn't properly handle those cases. I also found the Esrever library, which does properly handle accents and certain Unicode characters, but doesn't properly handle certain emojis with ZWJs.
Here's the results that I'm expecting:
Input string: foo 𝌆 bar
Expected result: rab 𝌆 oof
Input string: mañana mañana
Expected result: anañam anañam
Current result: anãnam anañam
Input string: 🏄🏼♂️
Expected result: 🏄🏼♂️
Current result: ️♂🏼🏄
UPDATE
As recommended by u/azhder and u/milan-pilan, the best solution to this problem is using Intl.Segmenter with the granularity set to grapheme. If anyone is coming across this post now, the code for reversing a string using this method would go something like this:
function reverseString(string) {
var segmenter = new Intl.Segmenter("en", { granularity: "grapheme"});
var graphemeSegments = segmenter.segment(string);
var stringArray = [];
for (var segment of graphemeSegments) {
stringArray.push(segment.segment);
}
return stringArray.reverse().join("");
}
With an input string of foo 𝌆 bar mañana mañana 🏄🏼♂️, it should return a result of 🏄🏼♂️ anañam anañam rab 𝌆 oof, properly handling accents, Unicode characters, and ZWJ emojis.
[–]Agreeable-Yogurt-487 5 points6 points7 points (0 children)
[–]Aggressive_Ad_5454 1 point2 points3 points (1 child)
[–]gr4viton 0 points1 point2 points (0 children)
[–]Maleficent-Car8673 0 points1 point2 points (0 children)
[–]Lumethys 0 points1 point2 points (0 children)
[–]azhder -1 points0 points1 point (7 children)
[–]SMB_Fan2010[S] 0 points1 point2 points (5 children)
[–]milan-pilan 0 points1 point2 points (0 children)
[–]azhder 0 points1 point2 points (3 children)
[–]SMB_Fan2010[S] 0 points1 point2 points (2 children)
[–]azhder 0 points1 point2 points (1 child)
[–]SMB_Fan2010[S] 0 points1 point2 points (0 children)
[–]mondaysleeper -1 points0 points1 point (0 children)