如何在JavaScript中执行不区分大小写的字符串比较?


当前回答

将两者转换为更低的字符串(出于性能原因,只进行一次),并将它们与内联三元运算符进行比较:

function strcasecmp(s1,s2){
    s1=(s1+'').toLowerCase();
    s2=(s2+'').toLowerCase();
    return s1>s2?1:(s1<s2?-1:0);
}

其他回答

我写了一个扩展。很琐碎的

if (typeof String.prototype.isEqual!= 'function') {
    String.prototype.isEqual = function (str){
        return this.toUpperCase()==str.toUpperCase();
     };
}

使用RegEx进行字符串匹配或比较。

在JavaScript中,你可以使用match()进行字符串比较, 别忘了把I放到正则表达式里。该标志将强制进行不区分大小写的测试。

例子:

为了确认任何情况下的字符串测试都包含在matchString变量内的任何位置

var matchString = "Test";
if (matchString.match(/test/i)) {
    alert('matchString contains the substring "test" case insensitive');
}
else {
    alert('matchString does not contain the substring "test" case insensitive');
}

要确认matchString变量只包含任何情况下的test,而不包含其他字符,则在正则表达式中使用零宽度断言^和$。这些将要求test分别直接出现在字符串的开始之后和字符串的结束之前。

var matchString = "Test";
if (matchString.match(/^test$/i)) {
    alert('matchString equals "test" case insensitive');
}
else {
    alert('matchString does not equal "test" case insensitive');
}

更新:

根据注释,之前的答案检查源包含关键字,使其相等检查添加了^和$。

(/^keyword$/i).test(source)

借助于正则表达式也可以实现。

(/keyword/i).test(source)

/i表示忽略大小写。如果没有必要,我们可以忽略并测试not大小写敏感匹配

(/keyword/).test(source)

由于没有答案明确提供了使用RegExp的简单代码片段,下面是我的尝试:

function compareInsensitive(str1, str2){ 
  return typeof str1 === 'string' && 
    typeof str2 === 'string' && 
    new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}

它有几个优点:

验证参数类型(任何非字符串参数,例如undefined,都会使str1.toUpperCase()这样的表达式崩溃)。 不会出现国际化问题。 转义RegExp字符串。

为了获得更好的浏览器兼容性,可以使用正则表达式。这将适用于过去20年发布的所有web浏览器:

String.prototype.equalsci = function(s) {
    var regexp = RegExp("^"+this.replace(/[.\\+*?\[\^\]$(){}=!<>|:-]/g, "\\$&")+"$", "i");
    return regexp.test(s);
}

"PERSON@Ü.EXAMPLE.COM".equalsci("person@ü.example.com")// returns true

这与这里找到的其他答案不同,因为它考虑到了并非所有用户都在使用现代网络浏览器。

注意:如果你需要支持不寻常的情况,如土耳其语,你将需要使用localeCompare,因为i和i在土耳其语中不是同一个字母。

"I".localeCompare("i", undefined, { sensitivity:"accent"})===0// returns true
"I".localeCompare("i", "tr", { sensitivity:"accent"})===0// returns false