如何在JavaScript中执行不区分大小写的字符串比较?
当前回答
记住,大小写是特定于区域设置的操作。根据具体情况,你可能需要考虑到这一点。例如,如果比较两个人的名字,可能需要考虑locale,但如果比较机器生成的值(如UUID),则可能不需要考虑locale。这就是为什么我在utils库中使用以下函数的原因(注意,出于性能原因,不包括类型检查)。
function compareStrings (string1, string2, ignoreCase, useLocale) {
if (ignoreCase) {
if (useLocale) {
string1 = string1.toLocaleLowerCase();
string2 = string2.toLocaleLowerCase();
}
else {
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
}
}
return string1 === string2;
}
其他回答
不抛出异常和不使用慢正则表达式怎么样?
return str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase();
上面的代码段假设您不希望匹配任何一个字符串为null或undefined。
如果你想匹配null/undefined,那么:
return (str1 == null && str2 == null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
如果出于某种原因你关心undefined vs null:
return (str1 === undefined && str2 === undefined)
|| (str1 === null && str2 === null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
如果你关心不等式的方向(也许你想排序一个列表) 你几乎必须做大小写转换,因为在unicode中小写字符比大写字符多toLowerCase可能是最好的转换。
function my_strcasecmp( a, b )
{
if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1
if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
return 0
}
Javascript似乎使用locale“C”进行字符串比较,因此结果排序将 如果字符串包含非ASCII字母,则为丑陋。如果不对字符串做更详细的检查,就没有太多的事情可以做。
正如在最近的评论中所说,string::localeCompare支持不区分大小写的比较(以及其他强大的功能)。
这里有一个简单的例子
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
这是一个通用函数
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
请注意,您可能应该输入正在使用的特定区域,而不是undefined。这在MDN文档中很重要
在瑞典语中,ä和a是不同的基本字母
敏感性的选择
浏览器支持
截至发稿时,UC浏览器的Android和Opera Mini不支持地区和选项参数。请登录https://caniuse.com/#search=localeCompare获取最新信息。
最简单的方法(如果你不担心特殊的Unicode字符)是调用toUpperCase:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
这里有很多答案,但我喜欢添加一个基于扩展String库的解决方案:
String.prototype.equalIgnoreCase = function(str)
{
return (str != null
&& typeof str === 'string'
&& this.toUpperCase() === str.toUpperCase());
}
这样你就可以像在Java中那样使用它!
例子:
var a = "hello";
var b = "HeLLo";
var c = "world";
if (a.equalIgnoreCase(b)) {
document.write("a == b");
}
if (a.equalIgnoreCase(c)) {
document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
document.write("b != c");
}
输出将是:
"a == b"
"b != c"
String.prototype.equalIgnoreCase = function(str) { 返回(str != null && Typeof STR === 'string' && this.toUpperCase() === str.toUpperCase()); } Var a = "hello"; var b = "HeLLo"; Var c = "world"; if (a.equalIgnoreCase(b)) { 文档。写("a == b"); document . write(“< br > "); } if (a.equalIgnoreCase(c)) { 文档。写("a == c"); } if (!b.equalIgnoreCase(c)) { 文档。写("b != c"); }