Sorting non English names in Javascripts [duplicate]

三世轮回 提交于 2020-05-08 19:07:28

问题


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>

回答1:


You can use Intl.Collator, introduced by ECMAScript Internationalization API:

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

For example:

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

Only works on latest browsers, though.




回答2:


Just reminder at first that, this is really a crude way of achieving what you want to do but it is all javascript. You can make it fancier and do more with it if you want. The only thing you can do in that case is to interprete it as unicode characters.

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


来源:https://stackoverflow.com/questions/23616235/sorting-non-english-names-in-javascripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!