Javascript 如何进行不区分大小写的字符串比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2140627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do case insensitive string comparison?
提问by flybywire
How do I perform case insensitive string comparison in JavaScript?
如何在 JavaScript 中执行不区分大小写的字符串比较?
回答by SLaks
The simplest way to do it (if you're not worried about special Unicode characters) is to call toUpperCase:
最简单的方法(如果您不担心特殊的 Unicode 字符)是调用toUpperCase:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
回答by Samuel Neff
EDIT: This answer was originally added 9 years ago. Today you should use localeComparewith the sensitivity: 'accent'option:
编辑:这个答案最初是在 9 年前添加的。今天你应该使用localeCompare这个sensitivity: 'accent'选项:
function ciEquals(a, b) {
return 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'));
The { sensitivity: 'accent' }tells localeCompare()to treat two variants of the same base letter as the same unlessthey have different accents (as in the third example) above.
将{ sensitivity: 'accent' }告诉localeCompare()治疗相同基础函作为相同的两个变体,除非以上它们具有不同的重音符号(如在第三示例)。
Alternatively, you can use { sensitivity: 'base' }, which treats two characters as equivalent as long as their base character is the same (so Awould be treated as equivalent to á).
或者,您可以使用{ sensitivity: 'base' },只要它们的基本字符相同,A它就会将两个字符视为等效(因此将被视为等效于á)。
Notethat the third parameter of localeCompareis not supported in IE10 or lower or certain mobile browsers (see the compatibility chart on the page linked above), so if you need to support those browsers, you'll need some kind of fallback:
请注意,localeCompareIE10 或更低版本或某些移动浏览器不支持的第三个参数(请参阅上面链接页面上的兼容性图表),因此如果您需要支持这些浏览器,则需要某种回退:
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 */;
}
Original answer
原答案
The best way to do a case insensitive comparison in JavaScript is to use RegExp match()method with the iflag.
在 JavaScript 中进行不区分大小写比较的最佳方法是使用match()带有i标志的RegExp方法。
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.
当被比较的两个字符串都是变量(不是常量)时,它会稍微复杂一些,因为您需要从字符串生成一个 RegExp,但是如果字符串具有特殊的正则表达式,将字符串传递给 RegExp 构造函数可能会导致不正确的匹配或失败的匹配其中的字符。
If you care about internationalization don't use toLowerCase()or toUpperCase()as it doesn't provide accurate case-insensitive comparisons in all languages.
如果您关心国际化,请不要使用toLowerCase()或toUpperCase()因为它没有在所有语言中提供准确的不区分大小写的比较。
回答by Jay Wick
As said in recent comments, string::localeComparesupports case insensitive comparisons (among other powerful things).
正如最近的评论中所说,string::localeCompare支持不区分大小写的比较(以及其他强大的功能)。
Here's a simple example
这是一个简单的例子
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
And a generic function you could use
还有一个你可以使用的通用函数
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
Note that instead of undefinedyou should probably enter the specific locale you are working with. This is important as denoted in the MDN docs
请注意,undefined您应该输入您正在使用的特定语言环境,而不是您。这很重要,如 MDN 文档中所述
in Swedish, ? and a are separate base letters
在瑞典语中,? 和 a 是单独的基本字母
Sensitivity options
灵敏度选项
Browser support
浏览器支持
As of time of posting, UC Browser for Android and Opera Mini do notsupport localeand optionsparameters. Please check https://caniuse.com/#search=localeComparefor up to date info.
截至发稿时,适用于 Android 和 Opera Mini 的 UC 浏览器不支持区域设置和选项参数。请检查https://caniuse.com/#search=localeCompare以获取最新信息。
回答by SP007
With the help of regular expression also we can achieve.
借助正则表达式我们也可以实现。
(/keyword/i).test(source)
/iis for ignore case. If not necessary we can ignore and test for NOT case sensitive match like
/i用于忽略大小写。如果没有必要,我们可以忽略并测试不区分大小写的匹配,例如
(/keyword/).test(source)
回答by Shital Shah
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).
请记住,大小写是特定于语言环境的操作。根据不同的情况,您可能希望考虑到这一点。例如,如果您正在比较两个人的姓名,您可能需要考虑语言环境,但如果您正在比较机器生成的值(如 UUID),则可能不需要。这就是我在我的 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;
}
回答by Nick Uraltsev
I have recently created a micro library that provides case-insensitive string helpers: https://github.com/nickuraltsev/ignore-case. (It uses toUpperCaseinternally.)
我最近创建了一个提供不区分大小写字符串助手的微型库: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
回答by Jasen
if you are concerned about the direction of the inequality (perhaps you want to sort a list) you pretty-much have to do case-conversion, and as there are more lowercase characters in unicode than uppercase toLowerCase is probably the best conversion to use.
如果您担心不等式的方向(也许您想对列表进行排序),您几乎必须进行大小写转换,因为 unicode 中的小写字符多于大写,所以 toLowerCase 可能是最好的转换。
function my_strcasecmp( a, b )
{
if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1
if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
return 0
}
Javascript seems to use locale "C" for string comparisons so the resulting ordering will be ugly if the strings contain other than ASCII letters. there's not much that can be done about that without doing much more detailed inspection of the strings.
Javascript 似乎使用语言环境“C”进行字符串比较,因此如果字符串包含非 ASCII 字母,则结果排序将很难看。如果不对字符串进行更详细的检查,就没有什么可以做的。
回答by Chris Chute
Suppose we want to find the string variable needlein the string variable haystack. There are three gotchas:
假设我们要在字符串变量needle中找到字符串变量haystack。有三个陷阱:
- Internationalized applications should avoid
string.toUpperCaseandstring.toLowerCase. Use a regular expression which ignores case instead. For example,var needleRegExp = new RegExp(needle, "i");followed byneedleRegExp.test(haystack). - In general, you might not know the value of
needle. Be careful thatneedledoes not contain any regular expression special characters. Escape these usingneedle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");. - In other cases, if you want to precisely match
needleandhaystack, just ignoring case, make sure to add"^"at the start and"$"at the end of your regular expression constructor.
- 国际化的应用程序应该避免
string.toUpperCase和string.toLowerCase。使用忽略大小写的正则表达式。例如,var needleRegExp = new RegExp(needle, "i");后跟needleRegExp.test(haystack). - 通常,您可能不知道 的值
needle。注意needle不要包含任何正则表达式的特殊字符。使用needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");. - 在其他情况下,如果您想精确匹配
needleandhaystack,只是忽略大小写,请确保"^"在"$"正则表达式构造函数的开头和结尾添加。
Taking points (1) and (2) into consideration, an example would be:
考虑到第 (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
}
回答by Sohail Arif
There are two ways for case insensitive comparison:
不区分大小写的比较有两种方式:
- Convert strings to upper case and then compare them using the strict operator (
===). How strict operator treats operands read stuff at: http://www.thesstech.com/javascript/relational-logical-operators - Pattern matching using string methods:
- 将字符串转换为大写,然后使用严格运算符 (
===)进行比较。严格运算符如何处理操作数读取内容:http: //www.thesstech.com/javascript/relational-logical-operators - 使用字符串方法进行模式匹配:
Use the "search" string method for case insensitive search. Read about search and other string methods at: http://www.thesstech.com/pattern-matching-using-string-methods
使用“搜索”字符串方法进行不区分大小写的搜索。阅读有关搜索和其他字符串方法的信息:http: //www.thesstech.com/pattern-matching-using-string-methods
<!doctype html>
<html>
<head>
<script>
// 1st way
var a = "apple";
var b = "APPLE";
if (a.toUpperCase() === b.toUpperCase()) {
alert("equal");
}
//2nd way
var a = " Null and void";
document.write(a.search(/null/i));
</script>
</head>
</html>
回答by Nebulosar
Lots of answers here, but I like to add a sollution based on extending the String lib:
这里有很多答案,但我喜欢添加基于扩展字符串库的解决方案:
String.prototype.equalIgnoreCase = function(str)
{
return (str != null
&& typeof str === 'string'
&& this.toUpperCase() === str.toUpperCase());
}
This way you can just use it like you do in Java!
这样您就可以像在 Java 中一样使用它!
Example:
例子:
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");
}
Output will be:
输出将是:
"a == b"
"b != c"
String.prototype.equalIgnoreCase = function(str) {
return (str != null &&
typeof str === 'string' &&
this.toUpperCase() === str.toUpperCase());
}
var a = "hello";
var b = "HeLLo";
var c = "world";
if (a.equalIgnoreCase(b)) {
document.write("a == b");
document.write("<br>");
}
if (a.equalIgnoreCase(c)) {
document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
document.write("b != c");
}


