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!
没有重音字符带来的额外混乱,本地化已经是一个巨大的挑战。 每当您想对字符串进行排序时,请记住localeCompare
和Intl.Collator
!
翻译自: https://davidwalsh.name/sorting-strings-accented-characters
slor 搜索引擎不带重音