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


当前回答

这里有很多答案,但我喜欢添加一个基于扩展String库的解决方案:

String.prototype.equalIgnoreCase = function(str)
{
    return (str != null 
            && typeof str === 'string'
            && this.toUpperCase() === str.toUpperCase());
}

这样你就可以像在Java中那样使用它!

例子:

var a = "hello";
var b = "HeLLo";
var c = "world";

if (a.equalIgnoreCase(b)) {
    document.write("a == b");
}
if (a.equalIgnoreCase(c)) {
    document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
    document.write("b != c");
}

输出将是:

"a == b"
"b != c"

String.prototype.equalIgnoreCase = function(str) { 返回(str != null && Typeof STR === 'string' && this.toUpperCase() === str.toUpperCase()); } Var a = "hello"; var b = "HeLLo"; Var c = "world"; if (a.equalIgnoreCase(b)) { 文档。写("a == b"); document . write(“< br > "); } if (a.equalIgnoreCase(c)) { 文档。写("a == c"); } if (!b.equalIgnoreCase(c)) { 文档。写("b != c"); }

其他回答

正如在最近的评论中所说,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获取最新信息。

甚至这个问题也已经有了答案。我有一种不同的方法来使用RegExp和match来忽略大小写敏感性。请看我的链接 https://jsfiddle.net/marchdave/7v8bd7dq/27/

$("#btnGuess").click(guessWord);

function guessWord() {

  var letter = $("#guessLetter").val();
  var word = 'ABC';
  var pattern = RegExp(letter, 'gi'); // pattern: /a/gi

  var result = word.match(pattern);
  alert('Ignore case sensitive:' + result);
}

由于没有答案明确提供了使用RegExp的简单代码片段,下面是我的尝试:

function compareInsensitive(str1, str2){ 
  return typeof str1 === 'string' && 
    typeof str2 === 'string' && 
    new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}

它有几个优点:

验证参数类型(任何非字符串参数,例如undefined,都会使str1.toUpperCase()这样的表达式崩溃)。 不会出现国际化问题。 转义RegExp字符串。

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

国际化的应用程序应该避免字符串。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
}

不抛出异常和不使用慢正则表达式怎么样?

return str1 != null && str2 != null 
    && typeof str1 === 'string' && typeof str2 === 'string'
    && str1.toUpperCase() === str2.toUpperCase();

上面的代码段假设您不希望匹配任何一个字符串为null或undefined。

如果你想匹配null/undefined,那么:

return (str1 == null && str2 == null)
    || (str1 != null && str2 != null 
        && typeof str1 === 'string' && typeof str2 === 'string'
        && str1.toUpperCase() === str2.toUpperCase());

如果出于某种原因你关心undefined vs null:

return (str1 === undefined && str2 === undefined)
    || (str1 === null && str2 === null)
    || (str1 != null && str2 != null 
        && typeof str1 === 'string' && typeof str2 === 'string'
        && str1.toUpperCase() === str2.toUpperCase());