JavaScript case insensitive string comparison

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


最简单的方法(如果你不担心特殊的Unicode字符)就是调用toUpperCase

var areEqual = string1.toUpperCase() === string2.toUpperCase();

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the 'i' flag.

JavaScript: case-insensitive search

When both strings being compared are variables (not constants), then it's a little more complicated 'cause you need to generate a RegExp from the string but passing the string to RegExp constructor can result in incorrect matches or failed matches if the string has special regex characters in it.

If you care about internationalization don't use toLowerCase() or toUpperCase() as it doesn't provide accurate case-insensitive comparisons in all languages.

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

EDIT : This answer is 7 years old. Today you should use localeCompare .


Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).

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;
}
链接地址: http://www.djcxy.com/p/13078.html

上一篇: 如何使String.Contains不区分大小写?

下一篇: 不区分大小写的JavaScript字符串比较