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


当前回答

假设我们想要在字符串变量大海捞针。这里有三个陷阱:

国际化的应用程序应该避免字符串。toUpperCase和string.toLowerCase。请使用忽略大小写的正则表达式。例如,var needleRegExp = new RegExp(needle, "i");然后是needleRegExp.test(haystack)。 一般来说,你可能不知道针的价值。注意针头不包含任何正则表达式特殊字符。使用needle.replace(/[-[\]{}()*+?, \ \ ^ $ | # \] / g , "\\$&");. 在其他情况下,如果您想精确匹配needle和haystack,只需忽略case,请确保在正则表达式构造函数的开头添加“^”,并在末尾添加“$”。

考虑到第(1)和(2)点,一个例子是:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
    // Your code here
}

其他回答

更新:

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

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

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

(/keyword/i).test(source)

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

(/keyword/).test(source)

假设我们想要在字符串变量大海捞针。这里有三个陷阱:

国际化的应用程序应该避免字符串。toUpperCase和string.toLowerCase。请使用忽略大小写的正则表达式。例如,var needleRegExp = new RegExp(needle, "i");然后是needleRegExp.test(haystack)。 一般来说,你可能不知道针的价值。注意针头不包含任何正则表达式特殊字符。使用needle.replace(/[-[\]{}()*+?, \ \ ^ $ | # \] / g , "\\$&");. 在其他情况下,如果您想精确匹配needle和haystack,只需忽略case,请确保在正则表达式构造函数的开头添加“^”,并在末尾添加“$”。

考虑到第(1)和(2)点,一个例子是:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
    // Your code here
}

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

if (typeof String.prototype.isEqual!= 'function') {
    String.prototype.isEqual = function (str){
        return this.toUpperCase()==str.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;
}

将两者转换为更低的字符串(出于性能原因,只进行一次),并将它们与内联三元运算符进行比较:

function strcasecmp(s1,s2){
    s1=(s1+'').toLowerCase();
    s2=(s2+'').toLowerCase();
    return s1>s2?1:(s1<s2?-1:0);
}