如何在JavaScript中执行不区分大小写的字符串比较?
当前回答
不区分大小写的比较有两种方式:
将字符串转换为大写,然后使用严格操作符(===)进行比较。 使用字符串方法进行模式匹配:
使用"search"字符串方法进行不区分大小写的搜索。
<!doctype html > < html > < >头 < >脚本 //第一种方式 Var a = "苹果"; var b = "苹果"; if (a.toUpperCase() === b.toUpperCase()) { alert("平等"); } / / 2路 var a = "无效"; document . write (a.search(/空/我)); > < /脚本 > < /头 < / html >
其他回答
使用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');
}
如果两个字符串具有相同的已知区域,则可能需要使用Intl。像这样的Collator对象:
function equalIgnoreCase(s1: string, s2: string) {
return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}
显然,您可能希望缓存Collator以提高效率。
这种方法的优点是,它应该比使用regexp快得多,并且基于一组非常可定制的(请参阅上一篇文章中关于区域设置和选项构造函数参数的描述)现成的排序器。
我写了一个扩展。很琐碎的
if (typeof String.prototype.isEqual!= 'function') {
String.prototype.isEqual = function (str){
return this.toUpperCase()==str.toUpperCase();
};
}
将两者转换为更低的字符串(出于性能原因,只进行一次),并将它们与内联三元运算符进行比较:
function strcasecmp(s1,s2){
s1=(s1+'').toLowerCase();
s2=(s2+'').toLowerCase();
return s1>s2?1:(s1<s2?-1:0);
}
正如在最近的评论中所说,string::localeCompare支持不区分大小写的比较(以及其他强大的功能)。
这里有一个简单的例子
'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0
这是一个通用函数
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
请注意,您可能应该输入正在使用的特定区域,而不是undefined。这在MDN文档中很重要
在瑞典语中,ä和a是不同的基本字母
敏感性的选择
浏览器支持
截至发稿时,UC浏览器的Android和Opera Mini不支持地区和选项参数。请登录https://caniuse.com/#search=localeCompare获取最新信息。