For reference, this is all you need to know.
“0” < “A” < “a” < “aa”
In other words, first numbers, then capitalized words, then lower case words.
Here’s how you javascript compare strings.
if (1 == '1') console.log('1. 1 == "1"'); | |
if (1 === '1') {} else console.log('2. 1 is not === "1" (types different)'); | |
var a = 'a'; | |
var a1 = a; | |
var a2 = 'a'; | |
if (a == a1) console.log('3. a == a1'); | |
if (a == a2) console.log('4. a == a2'); | |
if (a === a2) console.log('5. even a ==== a2 (equal value and type)'); | |
if ('0' < 'A') console.log('6. "0" is less than "A"'); | |
if ('A' < 'a') console.log('7. "A" is less than "a"'); | |
if ('a' < 'aa') console.log('8. "a" is less than "aa"'); | |
var strings = ['a', 'b', 'A', '!', 'z', 'Z', 'Alpha', 'alpha', '0', '1', '111']; | |
console.log('9. sorted strings', strings.sort()); |
If you are sorting an array of strings, simply use the Array.prototype.sort() function as above.
If you want to write your own function to compare strings, use something like …
function(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
// a must be equal to b
return 0;
}
What do you think?