How to compare Unicode strings in Javascript?

后端 未结 6 2041
不知归路
不知归路 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:28

    Mic's code improved for non-mentioned chars:

    var alpha = function(alphabet, dir, caseSensitive){
      dir = dir || 1;
      function compareLetters(a, b) {
        var ia = alphabet.indexOf(a);
        var ib = alphabet.indexOf(b);
        if(ia === -1 || ib === -1) {
          if(ib !== -1)
            return a > 'a';
          if(ia !== -1)
            return 'a' > b;
          return a > b;
        }
        return ia > ib;
      }
      return function(a, b){
        var pos = 0;
        var min = Math.min(a.length, b.length);
        caseSensitive = caseSensitive || false;
        if(!caseSensitive){
          a = a.toLowerCase();
          b = b.toLowerCase();
        }
        while(a.charAt(pos) === b.charAt(pos) && pos < min){ pos++; }
        return compareLetters(a.charAt(pos), b.charAt(pos)) ? dir:-dir;
      };
    };
    
    function assert(bCondition, sErrorMessage) {
          if (!bCondition) {
              throw new Error(sErrorMessage);
          }
    }
    
    assert(alpha("bac")("a", "b") === 1, "b is first than a");
    assert(alpha("abc")("ac", "a") === 1, "shorter string is first than longer string");
    assert(alpha("abc")("1abc", "0abc") === 1, "non-mentioned chars are compared as normal");
    assert(alpha("abc")("0abc", "1abc") === -1, "non-mentioned chars are compared as normal [2]");
    assert(alpha("abc")("0abc", "bbc") === -1, "non-mentioned chars are compared with mentioned chars in special way");
    assert(alpha("abc")("zabc", "abc") === 1, "non-mentioned chars are compared with mentioned chars in special way [2]");
    

提交回复
热议问题