String Comparison in javascript:
Let us learn how two strings are compared in javascript
Assume you have two strings:
"ant" and "ele"
Case 1:
alert("ant" < "ele" ); will give the result as true meaning "ant" is smaller than "ele". Because the first characters in string "ant" is "a" and in "ele" "e". "a" is considered small because "a" comes before "e". This makes the string "ant" smaller than "ele".
Case 2:
"ant" and "Ant"
alert("ant" < "Ant"); will give the result as false meaning "Ant" is smaller than "ant".
"A" is smaller than "a" it is because of unicode values that are used to represent character in computer.
a ---------> 97
A --------->65
Case 3:
"ant" and "ant"
alert("ant" < "ant" ); will give the result as false because they are equal if first characters are equal, compare the second characters the same way. Continue until the end of any string. If both strings ended simultaneously then they are equal,
here it is found to be same till the end so they are equal.
Case 4:
"ant" and "ants"
alert("ant" < "ants"); will give the result as true because if first characters are equal, compare the second characters the same way. Continue until the end of any string. If both strings do not end simultaneously the longer string is greater.
Summary:
- Check the first characters of both strings.
- If the first string has the first character as greater or less, then the first string is greater (or less) than the second. We are done.
- If first characters are equal, compare the second characters the same way continue until the end of any string
- If both strings ended simultaneously, then they are equal. Otherwise the longer string is greater.