localeCompare on iOS

localeCompare on iOS

本文关键字:iOS on localeCompare      更新时间:2023-09-26

我无法在iPad或iPhone上的任何浏览器中使用javascript本地化字符串比较。有人经历过同样的事情或对此有所了解吗?

我还试图强制瑞典语区域设置,以确保从操作系统中选择正确的区域设置不会有问题。但是,我仍然无法对特定于区域设置的字符进行正确的比较。

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.

任何可能导致的想法都将不胜感激。

我没有iPod或iPhone要测试,但他们的浏览器可能不支持localeCompare与您的locale参数:

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

如果你知道你要处理的字母表,你可以在它的字符上构造一个枚举(按字母顺序),并用它对字符串进行排序:

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));