How does string comparison work in JavaScript?

That the algorithm works for string comparison in javascript like

'bc' > 'ac' = true/false ?
'ac' > 'bc' = true/false ?
+4
source share
4 answers

This is calculated using the Relational Comparison Comparison Algorithm in ECMA-5. The relevant part is given below.

4. Else, both px and py are Strings
    a) If py is a prefix of px, return false. (A String value p is a prefix 
       of String value q if q can be the result of concatenating p and some
       other String r. Note that any String is a prefix of itself, because 
       r may be the empty String.)
    b) If px is a prefix of py, return true.
    c) Let k be the smallest nonnegative integer such that the character 
       at position k within px is different from the character at position 
       k within py. (There must be such a k, for neither String is a prefix 
       of the other.)
    d) Let m be the integer that is the code unit value for the character 
       at position k within px.
    e) Let n be the integer that is the code unit value for the character 
       at position k within py.
    f) If m < n, return true. Otherwise, return false.
+2
source

Strings are compared by character, so the very first letter is the most significant, therefore

'bc' > 'ac' = true/false ? => true
'ac' > 'bc' = true/false ? => false

if the first letter is equal then the second will be compared and so on until one of them is more or less or equal.

0
source

javascript ascii- .

ascii http://www.kerryr.net/pioneers/ascii2.htm

'bc' > 'ac' // because b > a
0

Not only in javascript. The easiest way is the string comparison algorithm will follow the lexicographic or dictionary order , which means that it will check each character by character, if there are some inconsistencies, you can solve the result

True: 
ant < any
aaa < aab 
aab < b 
b < baa
0
source

Source: https://habr.com/ru/post/1648621/


All Articles