Intl.Locale与多语言排序:超越toLocaleString的深度控制
利用Intl.Locale、Intl.Collator和Intl.DateTimeFormat构建一个完全可配置的国际化排序与格式化系统。 · 难度:入门 · +10XP
Intl.Locale与多语言排序:超越toLocaleString的深度控制
多数开发者只知道toLocaleString,但Intl命名空间包含Collator(排序)、DateTimeFormat(日期)和NumberFormat(数字)等强大对象。本教程将教你使用Intl.Locale解析和构造语言标签(如'zh-Hans-CN-u-nu-hanidec'),并用Collator实现德语电话簿排序(ß视为ss)和中文按拼音排序。你将成为国际化专家。
const collator = new Intl.Collator('de-DE', { sensitivity: 'base' });
console.log(collator.compare('straße', 'strasse')); // 0
const chineseCollator = new Intl.Collator('zh-CN');
console.log(chineseCollator.compare('啊', '阿')); // 拼音排序
const dtf = new Intl.DateTimeFormat('ar-EG', { dateStyle: 'full' });
console.log(dtf.format(new Date())); // 阿拉伯语格式