如何在JavaScript中执行不区分大小写的字符串比较?
当前回答
如果你知道你在处理ascii文本,那么你可以只使用大写/小写字符偏移量比较。
只要确保你的“完美”字符串(你想匹配的字符串)是小写的:
const CHARS_IN_BETWEEN = 32;
const LAST_UPPERCASE_CHAR = 90; // Z
function strMatchesIgnoreCase(lowercaseMatch, value) {
let i = 0, matches = lowercaseMatch.length === value.length;
while (matches && i < lowercaseMatch.length) {
const a = lowercaseMatch.charCodeAt(i);
const A = a - CHARS_IN_BETWEEN;
const b = value.charCodeAt(i);
const B = b + ((b > LAST_UPPERCASE_CHAR) ? -CHARS_IN_BETWEEN : CHARS_IN_BETWEEN);
matches = a === b // lowerA === b
|| A === b // upperA == b
|| a === B // lowerA == ~b
|| A === B; // upperA == ~b
i++;
}
return matches;
}
其他回答
如果你关心不等式的方向(也许你想排序一个列表) 你几乎必须做大小写转换,因为在unicode中小写字符比大写字符多toLowerCase可能是最好的转换。
function my_strcasecmp( a, b )
{
if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1
if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
return 0
}
Javascript似乎使用locale“C”进行字符串比较,因此结果排序将 如果字符串包含非ASCII字母,则为丑陋。如果不对字符串做更详细的检查,就没有太多的事情可以做。
使用RegEx进行字符串匹配或比较。
在JavaScript中,你可以使用match()进行字符串比较, 别忘了把I放到正则表达式里。该标志将强制进行不区分大小写的测试。
例子:
为了确认任何情况下的字符串测试都包含在matchString变量内的任何位置
var matchString = "Test";
if (matchString.match(/test/i)) {
alert('matchString contains the substring "test" case insensitive');
}
else {
alert('matchString does not contain the substring "test" case insensitive');
}
要确认matchString变量只包含任何情况下的test,而不包含其他字符,则在正则表达式中使用零宽度断言^和$。这些将要求test分别直接出现在字符串的开始之后和字符串的结束之前。
var matchString = "Test";
if (matchString.match(/^test$/i)) {
alert('matchString equals "test" case insensitive');
}
else {
alert('matchString does not equal "test" case insensitive');
}
将两者转换为更低的字符串(出于性能原因,只进行一次),并将它们与内联三元运算符进行比较:
function strcasecmp(s1,s2){
s1=(s1+'').toLowerCase();
s2=(s2+'').toLowerCase();
return s1>s2?1:(s1<s2?-1:0);
}
这里有很多答案,但我喜欢添加一个基于扩展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"); }
我写了一个扩展。很琐碎的
if (typeof String.prototype.isEqual!= 'function') {
String.prototype.isEqual = function (str){
return this.toUpperCase()==str.toUpperCase();
};
}