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


当前回答

为了获得更好的浏览器兼容性,可以使用正则表达式。这将适用于过去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

其他回答

更新:

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

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

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

(/keyword/i).test(source)

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

(/keyword/).test(source)

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

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

如果你关心不等式的方向(也许你想排序一个列表) 你几乎必须做大小写转换,因为在unicode中小写字符比大写字符多toLowerCase可能是最好的转换。

function my_strcasecmp( a, b ) 
{
    if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1  
    if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
    return 0
}

Javascript似乎使用locale“C”进行字符串比较,因此结果排序将 如果字符串包含非ASCII字母,则为丑陋。如果不对字符串做更详细的检查,就没有太多的事情可以做。

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

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

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

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

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