如何在JavaScript中进行不区分大小写的字符串比较?
编辑。这个答案最初是在9年前添加的。今天你应该使用localeCompare
和sensitivity: 'accent'
选项。
function ciEquals(a, b) {
return typeof a === 'string' && typeof b === 'string'
? a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0
: a === b;
}
console.log("'a' = 'a'?", ciEquals('a', 'a'));
console.log("'AaA' = 'aAa'?", ciEquals('AaA', 'aAa'));
console.log("'a' = 'á'?", ciEquals('a', 'á'));
console.log("'a' = 'b'?", ciEquals('a', 'b'));
<!--结束片段-->
{敏感度: '重音' }
告诉localeCompare()
将同一基础字母的两个变体视为相同_除非它们有不同的重音(如上面的第三个例子)。
另外,你也可以使用{敏感度:'基础'}
,只要两个字符的基础字符相同,就将其视为等价(所以A'将被视为等同于
á')。
注意 localeCompare
的第三个参数在IE10或更低版本或某些移动浏览器中不被支持(见上面链接的页面上的兼容性图表),所以如果你需要支持这些浏览器,你将需要某种退步。
function ciEqualsInner(a, b) {
return a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0;
}
function ciEquals(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') {
return a === b;
}
// v--- feature detection
return ciEqualsInner('A', 'a')
? ciEqualsInner(a, b)
: /* fallback approach here */;
}
原始答案
在JavaScript中进行不区分大小写的比较的最好方法是使用带有i
标志的RegExpmatch()
方法。
https://stackoverflow.com/questions/177719/javascript-case-insensitive-search
当被比较的两个字符串都是变量(而不是常量)时,那就有点复杂了,因为你需要从字符串中生成一个正则表达式,但是如果字符串中含有特殊的重合字符,将字符串传递给正则表达式构造器会导致不正确的匹配或匹配失败。
如果你关心国际化,不要使用toLowerCase()
或toUpperCase()
,因为它不能在所有语言中提供准确的不区分大小写的比较。