- Use comparison operators to check if two strings are equal
You can use the comparison operator ===
or ==
to determine whether two strings are equal. For example:
const str1 = 'apple'
const str2 = 'apple'
if (str1 === str2) {
console.log('两个字符串相等')
} else {
console.log('两个字符串不相等')
}
In the above code, we defined two string variables str1
and str2
and used ===
operator to compare their values. If the two strings are equal, output 两个字符串相等
; otherwise, output 两个字符串不相等
.
It should be noted that when using the ===
or ==
operator to compare two strings, a type conversion will be performed. Therefore, in actual use, an appropriate comparison method should be selected according to requirements.
- Use the localeCompare() method to determine whether two strings are equal
localeCompare()
The method is used to compare two strings and return a number indicating the size relationship between the two strings. Returns if the two strings are equal, a number 0
greater than if the first string is greater 0
than 0
number less than if the first string is less than the second. You can judge whether two strings are equal by judging whether the return value is equal 0
to or not. For example:
const str1 = 'apple'
const str2 = 'apple'
if (str1.localeCompare(str2) === 0) {
console.log('两个字符串相等')
} else {
console.log('两个字符串不相等')
}
In the above code, we use localeCompare()
the method to compare the size relationship between the two strings, and determine whether the return value is equal 0
. If equal, output 两个字符串相等
; otherwise output 两个字符串不相等
.
It should be noted that when using localeCompare()
the method to compare two strings, if the two strings cannot be compared in the current locale, a NaN
value will be returned. Therefore, in actual use, an appropriate comparison method should be selected according to requirements.
If you have any questions, please join the qq group for communication: 712627337