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


当前回答

str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
    console.log("true");
}

其他回答

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

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

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

我们也可以使用ASCII来实现:

function toLower(a){

    let c = "";

    
    for(let i = 0;i<a.length;i++){

        
        let f = a.charCodeAt(i);
        if(f < 95){

            c += String.fromCharCode(f+32);
        }
        else{

            c += a[i];
        }
    }

    return c;
}
function compareIt(a,b){


    return toLower(a)==toLower(b);


}
console.log(compareIt("An ExamPlE" , "an example"));

如果两个字符串具有相同的已知区域,则可能需要使用Intl。像这样的Collator对象:

function equalIgnoreCase(s1: string, s2: string) {
    return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}

显然,您可能希望缓存Collator以提高效率。

这种方法的优点是,它应该比使用regexp快得多,并且基于一组非常可定制的(请参阅上一篇文章中关于区域设置和选项构造函数参数的描述)现成的排序器。

我最近创建了一个微库,提供不区分大小写的字符串助手:https://github.com/nickuraltsev/ignore-case。(它在内部使用toUpperCase)

var ignoreCase = require('ignore-case');

ignoreCase.equals('FOO', 'Foo'); // => true
ignoreCase.startsWith('foobar', 'FOO'); // => true
ignoreCase.endsWith('foobar', 'BaR'); // => true
ignoreCase.includes('AbCd', 'c'); // => true
ignoreCase.indexOf('AbCd', 'c'); // => 2