如何在JavaScript中执行不区分大小写的字符串比较?
答案 0 :(得分:996)
最简单的方法(如果你不担心特殊的Unicode字符)就是调用toUpperCase
:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
答案 1 :(得分:147)
编辑:这个答案最初是在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'));
{ sensitivity: 'accent' }
告诉localeCompare()
将相同基本字母的两个变体视为相同的,除非它们具有不同的重音(如第三个示例中所示)。
或者,您可以使用{ sensitivity: 'base' }
,只要它们的基本字符相同,就会将两个字符视为等效字符(因此A
将被视为等同于á
)。< / p>
注意 IE10或更低版本或某些移动浏览器不支持localeCompare
的第三个参数(请参阅上面链接的页面上的兼容性图表),因此如果您需要支持那些浏览器,你需要某种后备:
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 */;
}
原始回答
在JavaScript中进行不区分大小写的比较的最佳方法是使用带有match()
标志的RegExp i
方法。
当比较两个字符串都是变量(不是常量)时,它会更复杂一些,因为你需要从字符串生成一个RegExp,但是将字符串传递给RegExp构造函数会导致匹配错误或匹配失败中有特殊的正则表达式字符。
如果您关心国际化,请不要使用toLowerCase()
或toUpperCase()
,因为它不能在所有语言中提供准确的不区分大小写的比较。
答案 2 :(得分:31)
借助正则表达式,我们也可以实现。
(/keyword/i).test(source)
/i
用于忽略大小写。如果没有必要,我们可以忽略并测试非区分大小写的匹配,如
(/keyword/).test(source)
答案 3 :(得分:26)
请记住,大小写是特定于语言环境的操作。根据具体情况,您可能希望将其纳入帐户。例如,如果要比较两个人的名字,可能需要考虑区域设置,但如果要比较机器生成的值(如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;
}
答案 4 :(得分:15)
如最近的评论所述,string::localCompare
支持不区分大小写的比较(除其他功能外)。
这是一个简单的例子
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
还有可以使用的通用函数
function equalsIgnoringCase(text, other) {
text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
请注意,您可能应该输入您正在使用的特定语言环境而不是undefined
。正如MDN文档中所述,这很重要
在瑞典语中,ä和a是单独的基本字母
截至发布之日,适用于Android和Opera Mini的UC浏览器 不支持 locale 和 options 参数。请检查https://caniuse.com/#search=localeCompare以获取最新信息。
答案 5 :(得分:11)
如果您担心不平等的方向(也许您想要对列表进行排序) 你非常需要进行大小写转换,因为unicode中的小写字符多于大写toLowerCase可能是最好的转换。
function my_strcasecmp( a, b )
{
if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1
if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
return 0
}
Javascript似乎使用区域设置“C”进行字符串比较,因此得到的排序将会 如果字符串包含非ASCII字母,则会很难看。如果不对字符串进行更详细的检查,就没有太多可以做的。
答案 6 :(得分:11)
我最近创建了一个提供不区分大小写的字符串帮助程序的微型库: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
答案 7 :(得分:7)
假设我们想在字符串变量needle
中找到字符串变量haystack
。有三个陷阱:
string.toUpperCase
和string.toLowerCase
。使用忽略大小写的正则表达式。例如,var needleRegExp = new RegExp(needle, "i");
后跟needleRegExp.test(haystack)
。needle
的值。请注意needle
不包含任何正则表达式special characters。使用needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
。needle
和haystack
,只需忽略大小写,请务必在开头添加"^"
,在结尾添加"$"
你的正则表达式构造函数。考虑点(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
}
答案 8 :(得分:4)
对于不区分大小写的比较,有两种方法:
===
)对它们进行比较。运算符如何严格处理操作数读取的内容:
http://www.thesstech.com/javascript/relational-logical-operators 使用&#34;搜索&#34;用于不区分大小写搜索的字符串方法。 阅读有关搜索和其他字符串方法的信息: 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>
答案 9 :(得分:4)
这里有很多答案,但我想基于扩展String lib添加一个sollution:
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) {
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");
}
答案 10 :(得分:3)
str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
console.log("true");
}
答案 11 :(得分:2)
如何不抛出异常而不使用慢速正则表达式?
return str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase();
如果任一字符串为null或未定义,上面的代码段假定您不想匹配。
如果要匹配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());
答案 12 :(得分:2)
即使这个问题已经回答了。我有一种不同的方法来使用RegExp和匹配来忽略区分大小写。请看我的链接 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);
}
答案 13 :(得分:2)
使用RegEx进行字符串匹配或比较。
在JavaScript中,您可以使用match()
进行字符串比较,
不要忘记将i
放入RegEx。
示例:
var matchString = "Test";
if (matchString.match(/test/i)) {
alert('String matched');
}
else {
alert('String not matched');
}
答案 14 :(得分:2)
我写了一个扩展名。很琐碎
if (typeof String.prototype.isEqual!= 'function') {
String.prototype.isEqual = function (str){
return this.toUpperCase()==str.toUpperCase();
};
}
答案 15 :(得分:1)
由于没有答案清楚地提供了使用RegExp
的简单代码段,这是我的尝试:
function compareInsensitive(str1, str2){
return typeof str1 === 'string' &&
typeof str2 === 'string' &&
new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}
它有几个优点:
undefined
都会使str1.toUpperCase()
等表达式崩溃。RegExp
字符串。答案 16 :(得分:1)
如果两个字符串具有相同的已知语言环境,则可能需要使用Intl.Collator
这样的对象:
function equalIgnoreCase(s1: string, s2: string) {
return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}
显然,您可能希望缓存Collator
以提高效率。
这种方法的优点是它应该比使用RegExps快得多,并且基于一个非常可定制的(参见上面文章中locales
和options
构造函数参数的描述)准备就绪使用合作者。
答案 17 :(得分:1)
我喜欢这种速记速记形式-
export const equalsIgnoreCase = (str1, str2) => {
return (!str1 && !str2) || (str1 && str2 && str1.toUpperCase() == str2.toUpperCase())
}
快速处理,并按预期进行。
答案 18 :(得分:1)
为了获得更好的浏览器兼容性,您可以依赖正则表达式。这将适用于过去20年中发布的所有网络浏览器:
String.prototype.equalsci = function(s) {
var regexp = RegExp("^"+this.replace(/[.\\+*?\[\^\]$(){}=!<>|:-]/g, "\\$&")+"$", "i");
return regexp.test(s);
}
"PERSON@Ü.EXAMPLE.COM".equalsci("person@ü.example.com")// returns true
这与此处找到的其他答案不同,因为它考虑到并非所有用户都在使用现代Web浏览器。
注意:如果您需要支持土耳其语等特殊情况,则需要使用localeCompare,因为我和我在土耳其语中的字母不同。
"I".localeCompare("i", undefined, { sensitivity:"accent"})===0// returns true
"I".localeCompare("i", "tr", { sensitivity:"accent"})===0// returns false
答案 19 :(得分:0)
这是this answer的改进版本。
String.equal = function (s1, s2, ignoreCase, useLocale) {
if (s1 == null || s2 == null)
return false;
if (!ignoreCase) {
if (s1.length !== s2.length)
return false;
return s1 === s2;
}
if (useLocale) {
if (useLocale.length)
return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)
else
return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()
}
else {
if (s1.length !== s2.length)
return false;
return s1.toLowerCase() === s2.toLowerCase();
}
}
String.equal = function (s1, s2, ignoreCase, useLocale) {
if (s1 == null || s2 == null)
return false;
if (!ignoreCase) {
if (s1.length !== s2.length)
return false;
return s1 === s2;
}
if (useLocale) {
if (useLocale.length)
return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)
else
return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()
}
else {
if (s1.length !== s2.length)
return false;
return s1.toLowerCase() === s2.toLowerCase();
}
}
// If you don't mind extending the prototype.
String.prototype.equal = function(string2, ignoreCase, useLocale) {
return String.equal(this.valueOf(), string2, ignoreCase, useLocale);
}
// ------------------ TESTS ----------------------
console.log("Tests...");
console.log('Case sensitive 1');
var result = "Abc123".equal("Abc123");
console.assert(result === true);
console.log('Case sensitive 2');
result = "aBC123".equal("Abc123");
console.assert(result === false);
console.log('Ignore case');
result = "AbC123".equal("aBc123", true);
console.assert(result === true);
console.log('Ignore case + Current locale');
result = "AbC123".equal("aBc123", true);
console.assert(result === true);
console.log('Turkish test 1 (ignore case, en-US)');
result = "IiiI".equal("ıiİI", true, "en-US");
console.assert(result === false);
console.log('Turkish test 2 (ignore case, tr-TR)');
result = "IiiI".equal("ıiİI", true, "tr-TR");
console.assert(result === true);
console.log('Turkish test 3 (case sensitive, tr-TR)');
result = "IiiI".equal("ıiİI", false, "tr-TR");
console.assert(result === false);
console.log('null-test-1');
result = "AAA".equal(null);
console.assert(result === false);
console.log('null-test-2');
result = String.equal(null, "BBB");
console.assert(result === false);
console.log('null-test-3');
result = String.equal(null, null);
console.assert(result === false);
答案 20 :(得分:0)
将两者均转换为较低值(出于性能原因仅一次),并将它们与三元运算符在一行中进行比较:
function strcasecmp(s1,s2){
s1=(s1+'').toLowerCase();
s2=(s2+'').toLowerCase();
return s1>s2?1:(s1<s2?-1:0);
}
答案 21 :(得分:0)
如果您知道要处理Post.update({
id: req.query.id
}, {
$set: {
currentBid: req.query.currentBid,
lastBidTimeStamp: req.params.lastBidTimeStamp,
biddingGroup: ['test']
}
}, {
multi: false //set to false to ensure only one document gets updated
}).exec().then(data => {
console.log(data);
}, err => {
console.log(err);
});
文本,则可以使用大写/小写字符偏移比较。
只需确保您的“完美”字符串(要与之匹配的字符串)是小写字母即可:
ascii