如何在JavaScript中执行不区分大小写的字符串比较?
当前回答
我写了一个扩展。很琐碎的
if (typeof String.prototype.isEqual!= 'function') {
String.prototype.isEqual = function (str){
return this.toUpperCase()==str.toUpperCase();
};
}
其他回答
这里有很多答案,但我喜欢添加一个基于扩展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"); }
更新:
根据注释,之前的答案检查源包含关键字,使其相等检查添加了^和$。
(/^keyword$/i).test(source)
借助于正则表达式也可以实现。
(/keyword/i).test(source)
/i表示忽略大小写。如果没有必要,我们可以忽略并测试not大小写敏感匹配
(/keyword/).test(source)
记住,大小写是特定于区域设置的操作。根据具体情况,你可能需要考虑到这一点。例如,如果比较两个人的名字,可能需要考虑locale,但如果比较机器生成的值(如UUID),则可能不需要考虑locale。这就是为什么我在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;
}
如果你关心不等式的方向(也许你想排序一个列表) 你几乎必须做大小写转换,因为在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字母,则为丑陋。如果不对字符串做更详细的检查,就没有太多的事情可以做。
不区分大小写的比较有两种方式:
将字符串转换为大写,然后使用严格操作符(===)进行比较。 使用字符串方法进行模式匹配:
使用"search"字符串方法进行不区分大小写的搜索。
<!doctype html > < html > < >头 < >脚本 //第一种方式 Var a = "苹果"; var b = "苹果"; if (a.toUpperCase() === b.toUpperCase()) { alert("平等"); } / / 2路 var a = "无效"; document . write (a.search(/空/我)); > < /脚本 > < /头 < / html >