'String comparison of numeric string with actual string in javascirpt
when i compare "5">"r" it gives false and "r">"5" it turns out to be true, what is the logic behind in JavaScript?
Solution 1:[1]
Javascript uses lexicographical order while comparing strings.
It all belong to unicode index for that specific character. Lowercase r has greater index than 5. Same way Uppercase A is not equal to lowercase a because Uppercase A has lower index than lowercase a.
console.log('a' === 'A'); // false
console.log('a' > 'A'); // true
console.log('a' < 'A'); // false
Another example would be comparing two string almost identical javascript_a and javascript_b.
console.log('javascript_a' === 'javascript_b'); // false
console.log('javascript_a' > 'javascript_b'); // false
console.log('javascript_a' < 'javascript_b'); // true
Here all character matches except the last characters. a and b. Lowercase a has lower unicode index than lowercase b. Even if you compare any digit, character or symbols, comparison happens depending on their unicode index.
If you compare @ with $ you will get to know that $ is less than @, since $ has lower unicode than @.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MORÈ |
