简体   繁体   English

如何基于特定语言环境对JavaScript中的字符串进行排序或比较?

[英]How do you sort or compare Strings in JavaScript based on a certain locale?

I know there is a function called String.prototype.localeCompare which you can use, and you can send in as the second argument a list of locales. 我知道您可以使用一个名为String.prototype.localeCompare的函数,并且可以将第二个区域设置作为第二个参数发送。

string.localeCompare(compareString [, locales [, options]]) string.localeCompare(compareString [,locales [,options]])

But if you look at the browser compatibility table, only Chrome supports it. 但是,如果您查看浏览器兼容性表,则只有Chrome支持。

在此处输入图片说明

How do you sort or compare Strings in JavaScript based on a certain locale? 如何基于特定语言环境对JavaScript中的字符串进行排序或比较?

How does all the big websites do this, like ebay or amazon? 所有大型网站(例如ebay或Amazon)如何做到这一点? They must have some kind of String sorting in the front-end.. right? 他们必须在前端进行某种String排序。

May be you need sorting, not compare? 也许您需要排序,而不是比较?

Javascript array sort method sort strings on its Unicode (not ASCII) codes. Javascript数组sort方法按其Unicode (非ASCII)代码对字符串进行排序。 You can sort array of strings to get it in alphabetical order. 您可以对字符串数组进行排序以按字母顺序获取它。

['Собака', 'Кошка'].sort() will sort array to ["Кошка", "Собака"] which is right in Ru_ru locale. ['Собака', 'Кошка'].sort()会将数组排序为["Кошка", "Собака"] ,在Ru_ru语言环境中正确。

You can add compare function like this: 您可以像这样添加比较功能:

['Собака', 'Кошка', 'Свекла'].sort(function(a, b) { 
    return a[1] > b[1]?1:-1;
})

Javascript will compare strings by Unicode character by character. Javascript将逐字符比较Unicode字符的字符串。 In my example compare is inside a[1] > b[1] on native low-level code. 在我的示例中,compare在本机低级代码的a[1] > b[1]内部。 Return -1 or 1 needs for sort function to replace array elements. 返回-1或1需要sort函数来替换数组元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM