Home  >  Article  >  Web Front-end  >  How to determine whether strings are equal in javascript

How to determine whether strings are equal in javascript

青灯夜游
青灯夜游Original
2022-03-28 19:57:1314016browse

JS method to determine whether strings are equal: 1. Use the "==" equality operator, the syntax is "String 1 == String 2", if equal, return true, if not equal, return false; 2 , use the "===" identity operator, the syntax is "String 1 === String 2", if equal, return true, otherwise return false.

How to determine whether strings are equal in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript determines whether strings are equal

In javascript, you can use "==" or "===" operator to determine whether strings are equal.

1. Use "==" for equality:

Example

var str1 = "123456" ; // 字符串
var str2 = "123456" ; // 字符串
alert(str1==str2) ; // 打印出 true,即相等

2. Use "===" for equality Comparison:

Example

var str1 = "123456" ; // 字符串
var str2 = "123456" ; // 字符串
alert(str1==str2) ; // 打印出 true,即相等

Explanation: The difference between the "==" or "===" operators

  • "==" means "equal", and the necessary value type conversion will be performed before equality comparison is performed. To put it simply, the value is converted to the same type first and then compared for equality. Even if the types of the compared values ​​are different, they can be cast to the same type without causing an error.

  • "===" means "identity" and no type conversion will be performed, so if the two values ​​are not of the same type, then when compared, it will return false. If you compare two variables whose types are incompatible with each other, a compilation error will occur.

Example 1

var str1 = 123456 ; // 整型
var str2 = "123456" ; // 字符串
alert(str1==str2) ; // 打印出 true,即相等

Example 2

var str1 = 123456 ; // 整型
var str2 = "123456" ; // 字符串
alert(str1==str2) ; // 打印出 false,即不相等

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to determine whether strings are equal in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn