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


当前回答

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

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

其他回答

我最近创建了一个微库,提供不区分大小写的字符串助手: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

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

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

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

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

使用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');
}

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

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

我们也可以使用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"));