Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localeCompare on iOS

I can not get my javascript localized string comparison to work in any browser on iPads or iPhones. Has anyone experienced the same or know anything about it?

I also tried to force Swedish locale to assure it's not a problem with picking up the correct locale from the OS. Still I can't get the correct comparison of locale specific characters.

let mixedChars = ['å','ä','o']
mixedChars.sort(function(a,b) {return a.localeCompare(b, 'sv-SE')})
alert(JSON.stringify(mixedChars))

// in iOS using Chrome or FF => å,ä,o
// in any other setup I have tried => o,å,ä which is according the Swedish alphabet.

Any ideas what might be causing the is greatly appreciated.

like image 464
Morgan Jennevret Avatar asked Oct 30 '22 03:10

Morgan Jennevret


1 Answers

I don't have an iPod or iPhone to test, but their browsers may not support localeCompare with your locale argument:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#Browser_compatibility

If you know the alphabet you will be dealing with, you can construct an enumeration over its characters (in alphabetical order), and use it to sort strings:

var alphabet, enumeration, comparator, mixedChars, i, c;

alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'Å', 'Ä', 'Ö', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z', 'å', 'ä', 'ö'];

enumeration = {};

for (i = 0; i < alphabet.length; i += 1) {
    c = alphabet[i];
    enumeration[c] = i;
}

comparator = function (a, b) {
    var j, k, d, x, y;

    k = Math.min(a.length, b.length);
    for (j = 0; j < k; j += 1) {
        x = a[j];
        y = b[j];
        d = enumeration[x] - enumeration[y];
        if (0 !== d) {
            return d;
        }
    }

    if (j < a.length) {
        return 1;
    }

    if (j < b.length) {
        return -1;
    }

    return 0;
};

mixedStrings = [
    'äA',
    'å',
    'ä',
    'äAö',
    'Ä',
    'Äo',
    'äAöO',
    'o'
];

mixedStrings.sort(comparator);

// Alerts, ["Ä","Äo","o","å","ä","äA","äAö","äAöO"]
alert(JSON.stringify(mixedStrings));
like image 97
Dylon Avatar answered Nov 15 '22 07:11

Dylon