如何在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
}
其他回答
由于没有答案明确提供了使用RegExp的简单代码片段,下面是我的尝试:
function compareInsensitive(str1, str2){
return typeof str1 === 'string' &&
typeof str2 === 'string' &&
new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}
它有几个优点:
验证参数类型(任何非字符串参数,例如undefined,都会使str1.toUpperCase()这样的表达式崩溃)。 不会出现国际化问题。 转义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
记住,大小写是特定于区域设置的操作。根据具体情况,你可能需要考虑到这一点。例如,如果比较两个人的名字,可能需要考虑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;
}
正如在最近的评论中所说,string::localeCompare支持不区分大小写的比较(以及其他强大的功能)。
这里有一个简单的例子
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
这是一个通用函数
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
请注意,您可能应该输入正在使用的特定区域,而不是undefined。这在MDN文档中很重要
在瑞典语中,ä和a是不同的基本字母
敏感性的选择
浏览器支持
截至发稿时,UC浏览器的Android和Opera Mini不支持地区和选项参数。请登录https://caniuse.com/#search=localeCompare获取最新信息。
假设我们想要在字符串变量大海捞针。这里有三个陷阱:
国际化的应用程序应该避免字符串。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
}