Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 比较两个字符串的程序

比较两个字符串的 JavaScript 程序

在这个例子中,您将学习编写一个 JavaScript 程序来使用各种方法比较两个字符串。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 字符串 Javascript String toUpperCase() JavaScript 正则表达式 Javascript String localeCompare()

示例 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 视为相同。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4