6

What the algorithm work behind string comparison in javascript, for example

'bc' > 'ac' = true/false ?
'ac' > 'bc' = true/false ?
Nic
  • 11,374
  • 19
  • 75
  • 96
Govind Samrow
  • 9,455
  • 13
  • 50
  • 85

4 Answers4

4

This is calculated using The Abstract Relational Comparison Algorithm in ECMA-5. The relevant part is quoted 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.
sabithpocker
  • 14,744
  • 1
  • 38
  • 71
1

JavaScript compares strings by the order of Unicode codepoints and lexicographically compares UTF-16 code units.

From your question:

'bc' > 'ac' // Because 'b' comes after 'a'.
Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
Alongkorn
  • 3,376
  • 1
  • 23
  • 40
1

Not only in javascript , In simple, all string comparison algorithm will follow the lexicographical order or dictionary order, which means it will check each character by character, if some mismatches, you can decide the result

True: 
ant < any
aaa < aab 
aab < b 
b < baa
Manikandan
  • 1,194
  • 10
  • 18
0

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

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

if the first letter will be equal then, second will be compared and so on, till one of them will be greater or less or equal.

Oskar Szura
  • 2,319
  • 5
  • 31
  • 41