示例 1: 使用 toUpperCase()
// js program to perform string comparison const string1 = 'JavaScript Program'; const string2 = 'javascript program'; // compare both strings const result = string1.toUpperCase() === string2.toUpperCase(); if(result) { console.log('The strings are similar.'); } else { console.log('The strings are not similar.'); }
输出
The strings are similar.
在上面的程序中,比较了两个字符串。在这里,
toUpperCase()
方法将所有字符串字符转换为大写。
====
用于检查两个字符串是否相同。
if...else
语句用于根据条件显示结果。
注意: 也可以使用 toLowerCase() 方法将所有字符串转换为小写并进行比较。
示例 2: 使用 RegEx 比较 JS 字符串
// program to perform string comparison const string1 = 'JavaScript Program'; const string2 = 'javascript program'; // create regex const pattern = new RegExp(string1, "gi"); // compare the stings const result = pattern.test(string2) if(result) { console.log('The strings are similar.'); } else { console.log('The strings are not similar.'); }
输出
The strings are similar.
在上面的程序中,RegEx 与
test()
方法一起使用来执行不区分大小写的字符串比较。
在 RegEx 模式中,"g"语法表示全局,"gi"语法表示不区分大小写的比较。
示例 3: 使用 localeCompare()
// program to perform case insensitive string comparison const string1 = 'JavaScript Program'; const string2 = 'javascript program'; const result = string1.localeCompare(string2, undefined, { sensitivity: 'base' }); if(result == 0) { console.log('The strings are similar.'); } else { console.log('The strings are not similar.'); }
输出
The strings are similar.
在上面的程序中,
localeCompare()
方法用于进行不区分大小写的字符串比较。
localeCompare()
方法返回一个数字,指示引用字符串是在给定字符串之前、之后还是相同。
这里,
{sensitive: 'base' }
将 A 和 a 视为相同。