slor 搜索引擎不带重音_带重音字符的字符串排序

slor 搜索引擎不带重音

Strings can create a whole host of problems within any programming language.  Whether it's a simple string, a string containing emojis, html entities, and even accented characters, if we don't scrub data or make the right string handling choices, we can be in a world of hurt.

字符串可以在任何编程语言中产生很多问题。 无论是简单的字符串,包含表情符号,html实体甚至是带重音符号的字符串,如果我们不清理数据或做出正确的字符串处理选择,我们可能会遭受重创。

While looking through Joel Lovera's JSTips repo, I spotted a string case that I hadn't run into yet (...I probably have but didn't notice it):  sorting accented characters to get the desired outcome.  The truth is that accented characters are handled a bit differently than you'd think during a sort:

在翻阅Joel Lovera的JSTips回购时 ,我发现了一个尚未遇到的字符串情况(...我可能有但没有注意到):排序带重音的字符以获得所需的结果。 事实是,重音字符的处理方式与您在排序时所想的略有不同:


// Spanish
['único','árbol', 'cosas', 'fútbol'].sort();
// ["cosas", "fútbol", "árbol", "único"] // bad order

// German
['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();
// ["Wann", "Woche", "wäre", "wöchentlich"] // bad order


Yikes -- accented characters don't simply follow their unaccented character counterparts.  By taking an extra step, i.e. localeCompare, we can ensure that our strings are sorted in the way we likely wanted in the first place:

Yikes-重音符号不仅仅跟随其未重音符号对应。 通过采取额外的步骤(即localeCompare ,我们可以确保首先以可能的方式对字符串进行排序:


['único','árbol', 'cosas', 'fútbol'].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["árbol", "cosas", "fútbol", "único"]

['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["Wann", "wäre", "Woche", "wöchentlich"]

// Or even use Intl.Collator!
['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);
// ["árbol", "cosas", "fútbol", "único"]

['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);
// ["Wann", "wäre", "Woche", "wöchentlich"]


Localization is already a big challenge without the added confusion that comes with accented characters.  Keep localeCompare and Intl.Collator in mind every time you want to sort strings!

没有重音字符带来的额外混乱,本地化已经是一个巨大的挑战。 每当您想对字符串进行排序时,请记住localeCompareIntl.Collator

翻译自: https://davidwalsh.name/sorting-strings-accented-characters

slor 搜索引擎不带重音

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值