js不比较大小写判断俩字符串是否相等
时间: 2023-12-10 13:04:39 浏览: 42
在JavaScript中,字符串的比较是区分大小写的。如果你想进行大小写不敏感的字符串比较,可以采取以下几种方式:
1. 将字符串全部转换为小写或大写,然后进行比较。例如:
```javascript
const str1 = 'Hello';
const str2 = 'hello';
if (str1.toLowerCase() === str2.toLowerCase()) {
console.log('两个字符串相等');
}
```
2. 使用正则表达式进行比较,忽略大小写。例如:
```javascript
const str1 = 'Hello';
const str2 = 'hello';
if (/^hello$/i.test(str1) === /^hello$/i.test(str2)) {
console.log('两个字符串相等');
}
```
3. 使用第三方库进行比较,例如lodash库的`_.isEqual()`方法,它可以进行大小写不敏感的字符串比较。例如:
```javascript
const str1 = 'Hello';
const str2 = 'hello';
if (_.isEqual(str1, str2)) {
console.log('两个字符串相等');
}
```
相关问题
js两个字符串判断里面的字符是否相等
可以通过遍历字符串中每个字符,逐一比较它们的 ASCII 码值来判断是否相等。以下是一个示例代码:
```javascript
function compareStrings(str1, str2) {
// 如果两个字符串长度不同,则它们肯定不相等
if (str1.length !== str2.length) {
return false;
}
// 遍历每个字符,逐一比较它们的 ASCII 码值
for (let i = 0; i < str1.length; i++) {
if (str1.charCodeAt(i) !== str2.charCodeAt(i)) {
return false;
}
}
// 如果所有字符都相等,则两个字符串相等
return true;
}
// 示例用法
console.log(compareStrings("hello", "world")); // false
console.log(compareStrings("hello", "hhllo")); // false
console.log(compareStrings("hello", "Hello")); // false (注意大小写)
console.log(compareStrings("hello", "hello")); // true
```
需要注意的是,以上代码比较的是字符串中每个字符的 ASCII 码值是否相等,因此大小写字母、数字、符号等都会被区分。如果需要忽略大小写、或者需要更复杂的字符串比较逻辑,需要额外的处理。
js忽略大小写比较字符串
可以使用字符串的 toLowerCase() 或 toUpperCase() 方法将字符串转换为小写或大写,然后进行比较。
例如:
```javascript
var str1 = 'Hello';
var str2 = 'heLLo';
if (str1.toLowerCase() === str2.toLowerCase()) {
console.log('两个字符串相等');
} else {
console.log('两个字符串不相等');
}
```
输出结果为:“两个字符串相等”。