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


当前回答

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

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

其他回答

我喜欢这个简短的变化-

export const equalsIgnoreCase = (str1, str2) => {
    return (!str1 && !str2) || (str1 && str2 && str1.toUpperCase() == str2.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');
}

这里有很多答案,但我喜欢添加一个基于扩展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"); }

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

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();
     };
}