【问题标题】:Sorting non English names in Javascripts [duplicate]在Javascript中对非英文名称进行排序[重复]
【发布时间】:2014-06-30 05:46:46
【问题描述】:

我正在使用以下脚本来对 HTML 表中的列进行排序(按字母顺序)。除了我无法完全控制非英文字符之外,该脚本就像一个魅力。例如,如果我有一个以“Ü”开头的单词,则不会将其视为“U”(应该如此)。在执行排序之前有一种简单的方法来音译字符(如 ü->u、ä->a 等)?请注意,我不想使用 jQuery。

<script type="text/javascript">
    var glossary, asc1 = 1,
        asc2 = 1,
        asc3 = 1;
    window.onload = function () {
        glossary = document.getElementById("glossary");
    }

function sort_table(tbody, col, asc){
var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
// fill the array with values from the table
for(i = 0; i < rlen; i++){
cells = rows[i].cells;
clen = cells.length;
arr[i] = new Array();
    for(j = 0; j < clen; j++){
    arr[i][j] = cells[j].innerHTML;
    }
}
// sort the array by the specified column number (col) and order (asc)
arr.sort(function(a, b){
    return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1*asc);
});
for(i = 0; i < rlen; i++){
    arr[i] = "<td>"+arr[i].join("</td><td>")+"</td>";
}
tbody.innerHTML = "<tr>"+arr.join("</tr><tr>")+"</tr>";
}
</script>

【问题讨论】:

标签: javascript html sorting html-table non-english


【解决方案1】:

您可以使用Intl.Collator,由ECMAScript Internationalization API介绍:

arr.sort(Intl.Collator(lang).compare);

例如:

["Ü","U","V"].sort();                            // ["U","V","Ü"]
["Ü","U","V"].sort(Intl.Collator('de').compare); // ["U","Ü","V"]

不过,仅适用于最新的浏览器。

【讨论】:

    【解决方案2】:

    首先提醒一下,这确实是实现您想要做的事情的粗略方式,但它都是 javascript。如果你愿意,你可以让它更漂亮,用它做更多的事情。在这种情况下,您唯一能做的就是将其解释为 unicode 字符。

    Unicode_Array=[... unicode for all characters you have problem with...]
    // THIS ASSUMES YOUR UNICODE ARRAY HAS ALL THE CHARACTERS YOU NEEDED TO CHANGE
    Real_English=[...every conversion for what you have in Unicode array...]
    
    for (var i=0;i<Unicode_Array.length;i++){
    
        converted_word=word_for_table.replace(Unicode_Array[i], Real_English[i]);
        word_for_table=converted_word;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 2020-10-11
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多