JavaScript 程序:比较两个字符串

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 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() 方法返回一个数字,该数字指示参考字符串是否排在给定字符串之前、之后或与给定字符串相同。

这里,{ sensitivity: 'base' } 将 **A** 和 **a** 视为相同。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战