JavaScript 中不区分大小写的字符串比较
    
    
            Valentine Kagwiria
    2023年10月12日
    
    JavaScript
    JavaScript String
    
- 
          
            在 JavaScript 中使用 toUpperCase()/toLowerCase()字符串方法进行大小写不敏感的比较
- 
          
            在 JavaScript 中使用 localeCompare()字符串方法进行大小写不敏感的比较
- 
          
            在 JavaScript 中使用正则表达式方法 RegExp进行大小写不敏感的比较
 
本文介绍了如何在 JavaScript 中进行不区分大小写的字符串比较。
在 JavaScript 中使用 toUpperCase()/toLowerCase() 字符串方法进行大小写不敏感的比较
    
在 toUpperCase() 方法中,首先将字符串转换为大写或小写,然后用三等式运算符 === 进行比较。
下面是一个例子。
var stringA = 'This is a JavaScript tutorial';
var stringB = 'THIS is A javascript TUTORIAL';
if (stringA.toUpperCase() === stringB.toUpperCase()) {
  alert('The strings are equal.')
} else {
  alert('The strings are NOT equal.')
}
输出:
The strings are equal.
或者,你也可以使用 toLowercase() 字符串方法将字符串转换为小写,如下例所示。
var stringA = 'This is a JavaScript tutorial';
var stringB = 'THESE are javascript TUTORIALS';
if (stringA.toLowerCase() === stringB.toLowerCase()) {
  alert('The strings are equal.')
} else {
  alert('The strings are NOT equal.')
}
输出:
The strings are NOT equal
但值得注意的是,大写法是首选。这是因为字母表中的一些字符在转换为小写时不能进行往返。这本质上意味着,它们可能无法以准确表示该数据字符的方式从一个 locale 转换到另一个 locale。
在 JavaScript 中使用 localeCompare() 字符串方法进行大小写不敏感的比较
虽然上面的方法给出了一个简单的答案,但当字符串中包含 Unicode 字符时,它可能无法正常工作。localeCompare 字符串方法可以解决这个问题。它与 sensitivity: 'base'选项一起使用,以捕获所有 Unicode 字符。例如,我们可以在 if() 语句中使用该方法,以获得相关字符串相等和不相等的结果。
if ('javascript'.localeCompare('JavaScrpt', undefined, {sensitivity: 'base'}) ==
    0) {
  alert('The strings are equal')
} else {
  alert('The strings are different.')
}
输出:
The strings are different.
在 JavaScript 中使用正则表达式方法 RegExp 进行大小写不敏感的比较
    
在这个方法中,我们使用 RegExp 模式和 test() 方法来进行不区分大小写的字符串比较。例如:
const strA = 'This is a case sensitive comparison';
const strB = 'This is a CASE SENSITIVE comparison';
const regex = new RegExp(strA, 'gi');
const comparison = regex.test(strB)
if (comparison) {
  alert('Similar strings');
}
else {
  alert('Different strings');
}
输出:
Similar strings
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe