Home  >  Article  >  Web Front-end  >  How to compare two strings in JS

How to compare two strings in JS

anonymity
anonymityOriginal
2019-05-29 13:37:1911133browse

String comparison in JavaScript

Greater than (>), less than (<) operator

javascript string in When performing a greater than (less than) comparison, the comparison will be based on the ASCII value code of the first different character. When the number (number) is compared with the string (string), the number (number) will be forcibly converted into a character. string(string) and then compare.

How to compare two strings in JS

Code:

(function(){
    console.log(&#39;13&#39;>&#39;3&#39;); // 输出:false
    console.log(5>&#39;6&#39;);  // 输出: false
    console.log(&#39;d&#39;>&#39;ABDC&#39;) // 输出: true
    console.log(19>&#39;ssf&#39;) // 输出 false
    console.log(&#39;A&#39;>&#39;abcdef&#39;) // 输出 false
})()

Equality (==), strict equality (===) operator

When performing equality (==) operation comparison, if one side is a character and the other side is a number, the string will be converted into a number first and then compared; for strict equality (===), it will not be performed. Type conversion will compare types for equality. Note that NaN is false when compared with any value

(function(){
   console.log(&#39;6&#39;==6) // true
   console.log(&#39;6&#39;===6) // false
   console.log(6===6) // true
   console.log(&#39;abc&#39;==2) // false
   console.log(&#39;abc&#39;==&#39;abc&#39;) // true
   console.log(&#39;abc&#39;===&#39;abc&#39;) // true
})()

3. Equality and strict equality comparison of some special values

(function(){
    console.log(null==undefined) // 输出:true
    console.log(null===undefined) // 输出:false
    console.log(null===null) // 输出:true
    console.log(undefined===undefined) // 输出:true
    console.log(NaN==undefined) // 输出:false
    console.log(NaN==null)  // 输出:false
    console.log(NaN==NaN)  // 输出:false
    console.log(NaN===NaN)  // 输出:false
})()

The above is the detailed content of How to compare two strings in JS. 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
Previous article:How to use remove in jsNext article:How to use remove in js