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


当前回答

不抛出异常和不使用慢正则表达式怎么样?

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

其他回答

不区分大小写的比较有两种方式:

将字符串转换为大写,然后使用严格操作符(===)进行比较。 使用字符串方法进行模式匹配:

使用"search"字符串方法进行不区分大小写的搜索。

<!doctype html > < html > < >头 < >脚本 //第一种方式 Var a = "苹果"; var b = "苹果"; if (a.toUpperCase() === b.toUpperCase()) { alert("平等"); } / / 2路 var a = "无效"; document . write (a.search(/空/我)); > < /脚本 > < /头 < / html >

使用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');
}
str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
    console.log("true");
}

最简单的方法(如果你不担心特殊的Unicode字符)是调用toUpperCase:

var areEqual = string1.toUpperCase() === string2.toUpperCase();

记住,大小写是特定于区域设置的操作。根据具体情况,你可能需要考虑到这一点。例如,如果比较两个人的名字,可能需要考虑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;
}