在Javascript中对非英文名称进行排序 [英] Sorting non English names in Javascripts

查看:107
本文介绍了在Javascript中对非英文名称进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本来对HTML表中的列进行排序(按字母顺序).该脚本的工作原理很吸引人,只是我不能完全控制非英语字符.例如,如果我有一个以Ü"开头的单词,那么就不会像"U"那样对待它(应该如此).有一种简单的方法可以在进行排序之前对字符进行音译(例如ü-> u,ä-> a等)?请注意,我不想使用jQuery.

I'm using the following script in order to sort (alphabetically) columns in HTML tables. The script works like a charm except that I don't have full control of non-English characters. If I have a word beginning with "Ü" for example, this is not treated like a "U" (as it should be). There is an easy way to transliterate characters before performing the sorting (like ü->u, ä->a etc.)? Please note that I don't want to use 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>

推荐答案

您可以使用 Intl.Collator ,由ECMAScript国际化API :

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

例如:

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

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

Only works on latest browsers, though.

这篇关于在Javascript中对非英文名称进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆