How to compare strings for equality in javascript

青灯夜游
Release: 2023-01-07 11:47:41
Original
19808 people have browsed it

How to compare string equality in JavaScript: 1. Use the "==" operator for equality comparison, syntax "str1==str2"; 2. Use the "===" operator for equality comparison, Syntax "str1===str2".

How to compare strings for equality in javascript

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

javascript compares strings for equality

Method 1: Use "==" for equality comparison :

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

Method 2: Use "===" for equality comparison

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

Expand knowledge: "==" and "== The difference between ="

"==" 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.

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

"===" 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.

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

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to compare strings for equality in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template