How to compare Unicode strings in Javascript?

后端 未结 6 2030
不知归路
不知归路 2020-11-29 21:34

When I wrote in JavaScript \"Ł\" > \"Z\" it returns true. In Unicode order it should be of course false. How to fix this? My site i

6条回答
  •  既然无缘
    2020-11-29 22:07

    Here is an example for the french alphabet that could help you for a custom sort:

    var alpha = function(alphabet, dir, caseSensitive){
      return function(a, b){
        var pos = 0,
          min = Math.min(a.length, b.length);
        dir = dir || 1;
        caseSensitive = caseSensitive || false;
        if(!caseSensitive){
          a = a.toLowerCase();
          b = b.toLowerCase();
        }
        while(a.charAt(pos) === b.charAt(pos) && pos < min){ pos++; }
        return alphabet.indexOf(a.charAt(pos)) > alphabet.indexOf(b.charAt(pos)) ?
          dir:-dir;
      };
    };
    

    To use it on an array of strings a:

    a.sort(
      alpha('ABCDEFGHIJKLMNOPQRSTUVWXYZaàâäbcçdeéèêëfghiïîjklmnñoôöpqrstuûüvwxyÿz')
    );
    

    Add 1 or -1 as the second parameter of alpha() to sort ascending or descending.
    Add true as the 3rd parameter to sort case sensitive.

    You may need to add numbers and special chars to the alphabet list

提交回复
热议问题