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


当前回答

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

其他回答

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

编辑:这个答案最初是9年前添加的。现在你应该使用带有sensitivity: 'accent'选项的localeCompare:

函数ciEquals(a, b) { 返回typeof a === 'string' && typeof b === 'string' ? a.localeCompare(b, undefined, {sensitivity: 'accent'}) === 0 : a === b; } console.log("'a' = 'a'?", ciEquals('a', 'a')); console.log(“' AaA ' = ' AaA ' ?”,ciEquals (' AaA ', ' AaA ')); console.log("'a' = 'á'?", ciEquals('a', 'á')); console.log("'a' = 'b'?", ciEquals('a', 'b'));

{sensitivity: 'accent'}告诉localeCompare()将相同基字母的两个变体视为相同的,除非它们具有不同的重音(如上面的第三个例子)。

或者,您可以使用{sensitivity: 'base'},只要两个字符的基本字符相同,就将它们视为等效字符(因此A将被视为等效á)。

请注意,localeCompare的第三个参数在IE10或更低版本或某些移动浏览器中不受支持(请参阅上面链接页面上的兼容性图表),所以如果你需要支持这些浏览器,你将需要某种退步:

function ciEqualsInner(a, b) {
    return a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0;
}

function ciEquals(a, b) {
    if (typeof a !== 'string' || typeof b !== 'string') {
        return a === b;
    }

    //      v--- feature detection
    return ciEqualsInner('A', 'a')
        ? ciEqualsInner(a, b)
        : /*  fallback approach here  */;
}

原来的答案

在JavaScript中进行不区分大小写比较的最好方法是使用RegExp match()方法和i标志。

不区分大小写的搜索

当两个被比较的字符串都是变量(而不是常量)时,这就有点复杂了,因为你需要从字符串中生成一个RegExp,但是如果字符串中有特殊的regex字符,将字符串传递给RegExp构造函数可能会导致不正确的匹配或失败的匹配。

如果你关心国际化,不要使用toLowerCase()或toUpperCase(),因为它不能在所有语言中提供准确的不区分大小写的比较。

http://www.i18nguy.com/unicode/turkish-i18n.html

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

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

如果你关心不等式的方向(也许你想排序一个列表) 你几乎必须做大小写转换,因为在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字母,则为丑陋。如果不对字符串做更详细的检查,就没有太多的事情可以做。