工作时发现了一个原生国际化API: Intl,是international缩写的意思(写这句话有助于理解)
Intl 目前一共六个构造函数属性和两个静态方法,本章使用的是 Collator 属性和它的compare方法
使用方法是 new Intl.Collator().compare()
Intl.Collator(locales,options),(本地化国家代码 , 配置项对象)
compare(string1, string2) 接受两个参数,string1 > string2 会返回 1 ,小于返回 -1, 等于返回 0
以下是具体用法
const arr = ["Congrès", "congres", "Assemblée", "poisson"];
//中国...
const collator = new Intl.Collator("zh-CN", {
sensitivity: "base", // 不区分大小写和音标
});
const compareTool = "congres"; //对比的值
const matches = arr.filter((v) => collator.compare(v, compareTool) === 0);
//ES6的方法只要表达式返回true就会返回该值
matches: ["Congrès","congres"] //这样就可实现筛选不区分大小写音标之类的值了
以下是Collator的options有哪些配置项,分别代表的意思
{
localeMatcher:"lookup" || "best fit" //使用的 local 的匹配算法,默认值是 best fit
usage: "sort" || "search" //比较是用于排序还是用于搜索匹配的字符串,默认为sort
sensitivity: "base" || "accent" || "case" || "variant"
//base: 只有字母不同的比较不相等。例子:`a ≠ b`, `a = á`, `a = A`
//accent: 字母和各种音标比较不相等。例如:`a ≠ b`, `a ≠ á`, `a = A`
//case: 不同的字母或大小写比较不相等。例如: `a ≠ b`, `a = á`, `a ≠ A`。
//variant: 字母,口音和其他变音符号、或大小写,也可以考虑其他差异。例如: `a ≠ b`, `a ≠ á`, `a ≠ A`.
variant:"sort" //默认值使用 sort;它的 locale 依赖于使用 search
ignorePunctuation: true || false //是否应忽略标点,默认值为false
caseFirst: "upper" || "lower" || false //首先排序大写或者小写
numeric: true || false //是否应使用数字对照,使得1<2<10,默认值为false
}